正则表达式将文本中的用户名转换为指向其个人资料的链接


Regex to convert usernames within text to links to their profile

使用此正则表达式,我可以在我的评论正文中找到所有用户名,并将它们更改为超链接:

$body = preg_replace('/'B'@([a-zA-Z0-9_]{1,20})/', '<a href="/profiles/$1">$0</a>', $row["commentBody"]);

这会将@user转换为<a href="/profiles/user">@user</a>(显然是断开的链接)。

但是,它也会将h@user转换为我不想要的h<a href="/profiles/user">@user</a>

如何修改正则表达式以仅在字符串两侧有两个空格时才更改字符串?谢谢。

preg_replace('/(?:^|(?<='s))'@('w{1,20})(?!'w)/', '<a href="/profiles/$1">$0</a>', ...

preg_replace('/(?:^|(?<='s))'@('w{1,20})(?='s|$)/', ...

EDIT 错过了之前的两个空格,并固定为限制为 16 个字符:

$body = preg_replace('/(?<=^|  )'@([a-zA-Z0-9_]{1,16})(?:  )/', '<a href="/profiles/$1">$0</a>', $row["commentBody"]);

(结束编辑)

更好的是:

$body = preg_replace('/(?<=^|'s|[([])'@([a-zA-Z0-9_]{1,20})/', '<a href="/profiles/$1">$0</a>', $row["commentBody"]);

我怀疑目前的问题是你有一个隐藏的角色或其他东西。 例如,看看如果这样做会发生什么:

$body = 'h<!-- comment -->@user'; // or even something like '<strong>h</strong>@user'
$body = preg_replace('/'B'@([a-zA-Z0-9_]{1,20})/', '<a href="/profiles/$1">$0</a>', $body);
echo htmlentities($body);

你没有h@user喂它,即使它看起来像它,这就解释了为什么你会得到你所描述的输出。

另外,你说它会转换$user. 它不应该;你写它的方式,它会匹配@user,但不是$user. 如果希望它同时匹配两者,请将'@替换为 [@$]