2010-11-27 14 views
2

我已拼湊下面的代碼塊以幫助我從我的Twitter帳戶顯示我網站上的最新推文。但是,它不是很正常,你能幫我調試一下這一點嗎?我正在尋找PHP將其轉換爲HTML,其鏈接標籤纏繞在使用preg_replace的Twitter用戶名和鏈接上。使用preg_replace顯示來自Twitter帳戶的最新推文時將URL轉換爲鏈接

如果您測試此腳本,您會發現當它在推文中呈現標準鏈接時存在問題,它會在a之後過早提早結束< a>標記。我相信這是相對簡單的修復,可能是逃避角色或什麼的。

我主要的代碼塊:

<?php 
     /** Script to pull in the latest tweet */ 
     $username='benpaton'; 
     $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('/http:\/\/([[a-z0-9_\.\-\+\&\!\#\~\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); 
     $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet); 
     echo $latestTweet; 
    ?> 
+0

想法:你可以只是分開推文的空格和轉換爲URL的任何以「http://」開頭的部分?它比運行一個正則表達式要便宜得多,更簡單,我認爲它對於這個用例也同樣適用。 – Matchu 2010-11-27 02:15:14

+0

這聽起來可行。我不知道如何做到這一點,但@usernames不以「http://」開頭 – 2010-11-27 02:36:59

回答

6

正則表達式更改爲:

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

這爲我工作。

的完整代碼

<?php 
    /** Script to pull in the latest tweet */ 
    $username='benpaton'; 
    $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('/http:\/\/([a-z0-9_\.\-\+\&\!\#\~\/\,]+)/i', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); 
    $latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet); 
    echo $latestTweet; 
?> 
0

試試這個:

<?php 
/** Script to pull in the latest tweet */ 
$username='benpaton'; 
$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('%http://[a-z0-9_.+&!#~/,\-]+%', '<a href="http://$1" target="_blank">http://$1</a>', $latestTweet); 
$latestTweet = preg_replace('/@([a-z0-9_]+)/i', '<a href="http://twitter.com/$1" target="_blank">@$1</a>', $latestTweet); 
echo $latestTweet; 
?> 
0

所有的代碼是越野車或不完整的!你想要做的是這樣的:

$tweets[$i]['text_html'] = htmlspecialchars($tweet['text']); 
$tweets[$i]['text_html'] = preg_replace('%(http://([a-z0-9_.+&!#~/,\-]+))%i','<a href="http://$2">$1</a>',$tweets[$i]['text_html']); 
$tweets[$i]['text_html'] = preg_replace('/@([a-z0-9_]+)/i','<a href="http://twitter.com/$1">@$1</a>',$tweets[$i]['text_html']); 
相關問題