php regex - 用字符串中的链接替换所有@usernames [英] php regex - Replace all @usernames with link in a string
问题描述
我正在我的网站上实施一个时间轴系统,用户可以在其中使用 @username(例如 twitter)在他们的时间轴中提及其他用户.
I am implimenting a timeline system on my website where users can mention others users in their timeline using @username like twitter.
我想将 @username 转换为链接并将其指向他们的个人资料
I want to convert @username to link and point it to their profile
我的字符串:
$timeline="@fred-ii 's posts on @stackoverflow are intresting.";
我使用以下代码将@username 替换为 url :
I am using the following code to replace @username with url :
echo preg_replace("/@([^\s]+)/i","<a href='http://example.com/$1'>@$1</a>",$timeline);
它有效,问题是它也匹配空格
it works, the problem is that it matchs spaces also
这个字符串
"@fred-ii 's posts on@stackoverflow";
on 和 @stackoverflow 之间没有空格,我想排除它,
There is no space between on and @stackoverflow ,I want to exclude it,
所以我更新了我的正则表达式
so i updated my regex
/\s+@([^\s]+)/
它起作用了,但它与我的字符串的第一部分(用户名 @fred-ii )不匹配.我认为正则表达式引擎正在寻找字符串开头的空格.
it worked but it didnot match the first part of my string (username @fred-ii ) .I think regex engine is looking for space|s at the start of string.
我需要在我的模式中更改什么以匹配所有 @usernames ?
What do I need to change in my pattern to match all @usernames ?
$timeline="@fred-ii 's posts on @stackoverflow are intresting.";
推荐答案
你可以使用这个lookbehind assertion:
You can use this lookbehind assertion:
/(?<=\s|^)@\S+/
(?<=\s|^)
确保 @
之前有空格或行开始.
(?<=\s|^)
makes sure there is whitespace or line start before @
.
代码:
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
这篇关于php regex - 用字符串中的链接替换所有@usernames的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!