我需要将文本中所有以@开头的单词替换为指向该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.'
希望现在更清楚了!
将名称放在它自己的捕获组中,并在替换中引用它时使用 ''2。
$tweet_text = preg_replace('/(@('w+))/', '<a href="http://twitter.com/'2">'1</a>', $string);
您可以使用推特文本库
$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);