使用php preg_replace在推文中链接链接

时间:2010-11-25 02:31:35

标签: php twitter preg-replace

您好我正在尝试使用以下代码显示最新推文。这个preg_replace非常适合包装Twitter @usernames的链接,但不适用于推文中的网址。如何让这段代码在推文中包含网址链接。

        <?php
        /** Script to pull in the latest tweet */
        $username='fairgroceruk';
        $format = 'json';
        $tweet = json_decode(file_get_contents("http://api.twitter.com/1/statuses/user_timeline/{$username}.{$format}"));
        $latestTweet = htmlentities($tweet[0]->text, ENT_QUOTES);
        $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet);
        $latestTweet = preg_replace('/http://([a-z0-9_]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); echo $latestTweet;

    ?>

感谢您的帮助,

2 个答案:

答案 0 :(得分:1)

我添加了一个句点和一个转义的反斜杠,以便识别整个链接。使用上面的代码,它只读取到点的链接。只要链接与文本的其余部分之间有空格,此正则表达式就可以正常工作。

$text = preg_replace('/http:\/\/([a-z0-9_.\/]+)/i', '<a href="http://$1"     target="_blank">http://$1</a>', $text);

答案 1 :(得分:0)

主要是因为正则表达式不是有效的 - 在它的中间有一个/。

将分隔符更改为其他内容,就像这样,在中间碰撞中停止//:

$latestTweet = preg_replace('~http://([a-z0-9_]+)~i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); echo $latestTweet;

请注意,您没有明确地使用〜,但它在正则表达式中的使用率(至少在我的经验中)远不如/最终存在。

作为替代方案,您可以转义//部分:

$latestTweet = preg_replace('/http:\/\/([a-z0-9_]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); echo $latestTweet;