fix: 修复回复评论中可能会多次添加@的bug - #1419
Open
HuajiMX wants to merge 1 commit into
Open
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
问题
在测试评论 Markdown 功能时,发现这样一个现象,评论中出现了两次“@”:
该评论内容的结构是:正文 + 标题 + 正文。显然两处正文之前各自添加了一次”@“。
溯源
子评论最前面会带上“@父评论作者”,这个功能在
inc/theme-plus.php中实现:其中,
if(substr($comment_text, 0, 3) === "<p>")当内容以<p>开头时,会通过str_replace替换全文所有的<p>,这导致如果评论内容中包含多个段落,那么就会产生多个”@“,而我们仅仅需要在评论开头添加”@“。解决
因此,我们需要把这里的全文匹配替换修复为只替换第一次匹配。
/* * 评论添加@ */ function comment_add_at( $comment_text, $comment = '') { if( isset($comment->comment_parent) && $comment->comment_parent > 0) { if(substr($comment_text, 0, 3) === "<p>") - $comment_text = str_replace(substr($comment_text, 0, 3), '<p><a href="#comment-' . $comment->comment_parent . '" class="comment-at">@'.get_comment_author( $comment->comment_parent ) . '</a> ', $comment_text); + $comment_text = preg_replace('/<p>/', '<p><a href="#comment-' . $comment->comment_parent . '" class="comment-at">@' . get_comment_author($comment->comment_parent) . '</a> ', $comment_text, 1); else $comment_text = '<a href="#comment-' . $comment->comment_parent . '" class="comment-at">@'.get_comment_author( $comment->comment_parent ) . '</a> ' . $comment_text; } return $comment_text; }改用
preg_replace匹配替换,第 4 个参数1表示只替换 1 次。测试
修复后再次测试相同结构的评论,仅有开头一次”@“,修复成功。