php regex - 用字符串中的链接替换所有@usernames

时间:2015-11-21 15:01:40

标签: php regex preg-replace

我在我的网站上提到了一个时间轴系统,用户可以使用 @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";

@stackoverflow 之间没有空格,我想将其排除,

所以我更新了我的正则表达式

/\s+@([^\s]+)/

它有效,但它与我的字符串的第一部分(用户名 @ fred-ii )不匹配。我认为正则表达式引擎正在字符串的开头寻找空格。

我需要在模式中更改哪些内容以匹配所有@usernames?

$timeline="@fred-ii 's posts on @stackoverflow are intresting."; 

2 个答案:

答案 0 :(得分:1)

您可以使用lookbehind negative assertion执行此操作:

/(?<!\w)@([^\s]+)/

(?<!\w)只有在@([^\s]+)之前没有单词\w时,才会告诉Regex引擎匹配$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

生成此输出:

self.filler.frame

action中查看。

答案 1 :(得分:1)

你可以使用这个lookbehind断言:

/(?<=\s|^)@\S+/

(?<=\s|^)确保在@之前有空格或行开头。

<强>代码:

php> $s = "@fred-ii 's posts on@stackoverflow";

php> echo preg_replace('/(?<=\s|^)@\S+/', "<a href='http://example.com/$0'>$0</a>", $s);
<a href='http://example.com/fred-ii'>@fred-ii</a> 's posts on@stackoverflow