Skip to content

fix: 修复回复评论中可能会多次添加@的bug - #1419

Open
HuajiMX wants to merge 1 commit into
mirai-mamori:mainfrom
HuajiMX:fix/comment_add_at_bug
Open

fix: 修复回复评论中可能会多次添加@的bug#1419
HuajiMX wants to merge 1 commit into
mirai-mamori:mainfrom
HuajiMX:fix/comment_add_at_bug

Conversation

@HuajiMX

@HuajiMX HuajiMX commented Jul 29, 2026

Copy link
Copy Markdown

问题

在测试评论 Markdown 功能时,发现这样一个现象,评论中出现了两次“@”:

5eec8cb7802e7c1debe55ecc195c76d6

该评论内容的结构是:正文 + 标题 + 正文。显然两处正文之前各自添加了一次”@“。

溯源

子评论最前面会带上“@父评论作者”,这个功能在 inc/theme-plus.php 中实现:

/*
 * 评论添加@
 */
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>&nbsp;', $comment_text);
      else
        $comment_text = '<a href="#comment-' . $comment->comment_parent . '" class="comment-at">@'.get_comment_author( $comment->comment_parent ) . '</a>&nbsp;' . $comment_text;
  }
  return $comment_text;
}

其中,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>&nbsp;', $comment_text);
+         $comment_text = preg_replace('/<p>/', '<p><a href="#comment-' . $comment->comment_parent . '" class="comment-at">@' . get_comment_author($comment->comment_parent) . '</a>&nbsp;', $comment_text, 1);
      else
        $comment_text = '<a href="#comment-' . $comment->comment_parent . '" class="comment-at">@'.get_comment_author( $comment->comment_parent ) . '</a>&nbsp;' . $comment_text;
  }
  return $comment_text;
}

改用 preg_replace 匹配替换,第 4 个参数 1 表示只替换 1 次。

测试

修复后再次测试相同结构的评论,仅有开头一次”@“,修复成功。

b8bb0655bf93db6bc1c22dc197fa2afc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant