且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 16:57:40

你可以使用这个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@***";

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@***