【发布时间】:2015-11-21 15:01:39
【问题描述】:
我正在我的网站上实现一个时间线系统,用户可以使用 @username 在他们的时间线中提及其他用户,例如 twitter。
我想将 @username 转换为链接并将其指向他们的个人资料
我的字符串:
$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 )。我认为正则表达式引擎正在寻找字符串开头的空格。
我需要更改我的模式以匹配所有@usernames 吗?
$timeline="@fred-ii 's posts on @stackoverflow are intresting.";
【问题讨论】:
-
所以你想匹配用户名中的空格,但链接中没有空格?
标签: php regex preg-replace