PHP用链接到Twitter帐户的链接替换@username [英] Php to replace @username with link to twitter account
问题描述
我认为这与正则表达式有关,但这是一门艺术-我需要一些帮助.
I assume this is some to do with regex, but it's an art all it's own - and I need some help.
当我们显示一个故事时,我们将所有文本存储在一个变量中-假设$ story.
When we display a story, we store all the text in a varilable - let's say $story.
我想要做的是一个str_replace(我认为这是我所需要的),上面写着这样的内容:如果文本包含@something,则将其转换为类似<a href="http://www.twitter.com/something">@something</a>
-的链接,但只有在存在@符号前没有任何内容"(排除电子邮件地址)
What i'd like is to do a str_replace (I think that's what I need) that says something like this "If the text contains @something then turn it into a link like <a href="http://www.twitter.com/something">@something</a>
- but only do this if there's nothing before the @ symbol" (to exclude email addresses)
此外,如果后面有空格或标点符号,我们需要停止内容".这样的东西.不会变成<a href="http://www.twitter.com/something.">@something.</a>
Also, we'd need to stop the 'something' if there's a space or punctuation after it. so that @something. doesn't turn into <a href="http://www.twitter.com/something.">@something.</a>
关于如何进行这项工作的任何建议?
Any suggestions on how to make this work?
推荐答案
$input = preg_replace('/(^|\s)@([a-z0-9_]+)/i',
'$1<a href="http://www.twitter.com/$2">@$2</a>',
$input);
它与@
匹配,该@
前面没有空格(在开头).
It matches a @
which is preceded by whitespace or nothing ( when it is at the beginning).
也可以使用正向后看来将其短路:
It can also be shorted using positive lookbehind as:
$input = preg_replace('/(?<=^|\s)@([a-z0-9_]+)/i',
'<a href="http://www.twitter.com/$1">@$1</a>',
$input);
仅与twitter名称匹配,但仅在其前面有空格或没有空格的情况下匹配.
Which matches only the twitter name but only if there is space or nothing before that.
这篇关于PHP用链接到Twitter帐户的链接替换@username的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!