2010-11-25 53 views
1

您好,我正在嘗試使用下面的代碼顯示最新的推文。此preg_replace非常適合包裝twitter @usernames的鏈接,但不適用於推文中的網址。我如何獲得這個代碼來在推文中包裝URL的鏈接。用鏈接將鏈接包裹在用tweets preg_replace

 <?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; 

    ?> 

感謝您的幫助,

回答

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; 
+0

這些似乎不起作用... – 2010-11-25 02:46:07

1

我加了一個句點和一個反斜槓逃脫等全環節是公認的。有了上面的代碼,它只能讀取連接點。只要你的鏈接和其他文本之間有空格,這個正則表達式就可以工作。

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