我正在我的网站上实现一个时间线系统,用户可以在时间线中使用 @username(如 Twitter)提及其他用户。
我想将@用户名转换为链接并将其指向他们的个人资料
我的字符串:
$timeline="@fred-ii 's posts on @stackoverflow are intresting.";
我使用以下代码将 @username 替换为 url :
echo preg_replace("/@([^\s]+)/i","<a href='http://example.com/$1'>@$1</a>",$timeline);
它有效,问题是它也匹配空格
这个字符串
"@fred-ii 's posts on@stackoverflow";
on 和 @stackoverflow 之间没有空格,我想排除它,
所以我更新了我的正则表达式
/\s+@([^\s]+)/
它有效,但它与我的字符串的第一部分(用户名 @fred-ii )不匹配。我认为正则表达式引擎正在字符串开头查找空格。
我需要更改模式中的哪些内容才能匹配所有@用户名?
$timeline="@fred-ii 's posts on @stackoverflow are intresting.";
最佳答案
您可以使用lookbehind negative assertion来做到这一点:
/(?<!\w)@([^\s]+)/
(?<!\w)
告诉正则表达式引擎匹配 @([^\s]+)
仅当其前面没有单词 \w
时。它将在您给出的示例中工作,也许您必须随时调整它。
示例代码:
$pattern = "/(?<!\w)@([^\s]+)/";
$subject = "@fred-ii 's posts on @stackoverflow are interesting. @fred-ii 's posts on@stackoverflow";
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER );
foreach($matches as $item)
{
echo $item[1] . "<br/>";
}
产生此输出:
fred-ii
stackoverflow
fred-ii
参见 action .
关于php regex - 将所有@usernames替换为字符串中的链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33844826/