You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过PHP的preg_replace让论坛@用户名转为粗体?

实现@用户名转为粗体的PHP解决方案

嘿,这个需求在论坛系统里挺常见的,我来给你一步步说怎么实现~

核心思路:用preg_replace匹配并替换@用户名

我们可以通过正则表达式精准匹配帖子内容里的@用户名格式,再把它替换成包裹在<strong>标签里的内容,实现粗体效果。

基础版代码

// $postContent 是你的原始论坛帖子内容
$postContent = preg_replace('/@(\w+)/', '<strong>@$1</strong>', $postContent);
  • 正则/@(\w+)/的含义:匹配以@开头,后面跟着一个或多个字母、数字、下划线的字符串(\w等价于[A-Za-z0-9_])
  • 捕获组$1会提取出@后面的用户名,替换后就得到了带粗体标签的@用户名

适配更多用户名格式的进阶版

如果你的论坛用户名允许包含短横线(-)或点(.),可以把正则调整为:

$postContent = preg_replace('/@([\w.-]+)/', '<strong>@$1</strong>', $postContent);

这里[\w.-]+表示匹配字母、数字、下划线、短横线、点的组合,能覆盖更多常见的用户名规则。

避免匹配非用户名内容的精确版

如果担心@后面跟着非用户名字符(比如@bob!),我们可以用断言确保只匹配完整的用户名:

$postContent = preg_replace('/@([\w.-]+)(?![\w.-])/', '<strong>@$1</strong>', $postContent);

(?![\w.-])表示“后面不能是用户名允许的字符”,这样就不会把@bob!里的!错误包含进去。

和BBcode转换的顺序很关键!

这里要划重点:如果你的BBcode转HTML函数会自动转义HTML标签(比如把<strong>变成&lt;strong&gt;),那一定要先处理@替换,再执行BBcode转换!

举个完整的流程示例:

<?php
// 原始帖子内容(包含@和BBcode)
$rawPost = "大家好,@john 和 @jane-smith 一起参与了[b]重要讨论[/b],还有@bob123!";

// 第一步:处理@用户名为粗体
$processedPost = preg_replace('/@([\w.-]+)(?![\w.-])/', '<strong>@$1</strong>', $rawPost);

// 第二步:转换BBcode为HTML(示例BBcode转换函数)
function bbcode_to_html($content) {
    // 简单实现几个BBcode规则
    $content = preg_replace('/\[b\](.*?)\[\/b\]/', '<strong>$1</strong>', $content);
    $content = preg_replace('/\[i\](.*?)\[\/i\]/', '<em>$1</em>', $content);
    // 其他BBcode规则...
    return $content;
}

$finalContent = bbcode_to_html($processedPost);

// 输出结果
echo $finalContent;
?>

运行后得到的HTML内容:

大家好,<strong>@john</strong> 和 <strong>@jane-smith</strong> 一起参与了<strong>重要讨论</strong>,还有<strong>@bob123</strong>!

内容的提问来源于stack exchange,提问作者Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:38:24