我需要在文本中将@开头的所有单词替换为该twitter帐户的相应链接。现在我正在使用这样的东西:
$tweet_text = preg_replace('/(@\w+)/', '<a href=\'#\'>\1</a>', $string);
这有效,但链接无处可去。我决定使用strpos()和substr()的组合来获得实际的单词,然后能够链接到该Twitter帐户,但我想知道是否有更好的解决方案。有什么想法吗?
示例:
更换前:
'Imperfection is the new perfection... RT @xHausOfCandy: @katyperry i think your bottom teeth and your wonk eye make you even more adorable.'
更换后:
'Imperfection is the new perfection... RT <a href=''#''>@xHausOfCandy</a>: <a href=''#''>@katyperry</a> i think your bottom teeth and your wonk eye make you even more adorable.'
所需:
'Imperfection is the new perfection... RT <a href=''http://twitter.com/xHausOfCandy''>@xHausOfCandy</a>: <a href=''http://twitter.com/katyperry''>@katyperry</a> i think your bottom teeth and your wonk eye make you even more adorable.'
希望现在更清楚了!
答案 0 :(得分:4)
在其自己的捕获组中使用该名称,并在替换时引用它时使用\ 2。
$tweet_text = preg_replace('/(@(\w+))/', '<a href="http://twitter.com/\2">\1</a>', $string);
答案 1 :(得分:1)
您可以使用twitter-text库
答案 2 :(得分:1)
$string = 'Imperfection is the new perfection... RT @xHausOfCandy: @katyperry i think your bottom teeth and your wonk eye make you even more adorable.';
$tweet_text = preg_replace('/@(\w+)/', '<a href="http://twitter.com/#\1">@\1</a>', $string);