0

我需要用指向该 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.'

希望现在更清楚了!

4

3 回答 3

4

在它自己的捕获组中有名称,并在替换中引用它时使用 \2。

$tweet_text = preg_replace('/(@(\w+))/', '<a href="http://twitter.com/\2">\1</a>', $string);
于 2012-06-02T16:55:55.207 回答
1

您可以使用twitter-text

于 2012-06-02T16:51:16.317 回答
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);
于 2012-06-02T17:00:02.813 回答