2012-02-08 64 views
0

我用下面的代碼僅獲得使用PHP

foreach ($twitter_xml2->channel->item as $key) { 
    $author = $key->{"guid"}; 
    echo"<li><h5>$author</h5></li>"; 
} 

,它讓我一個字符串的一部分http://twitter.com/USERNAME/statuses/167382363782206976

我的問題是如何獲取只有用戶名?

用戶名可以是任何東西

+0

'$ key - > {「guid」}'等價於'$ key-> guid'。你不需要它周圍的「{」「}」。 – meagar 2012-02-08 23:08:00

回答

1
$url = "http://twitter.com/USERNAME/statuses/167382363782206976" 
preg_match("#http://twitter.com/([^\/]+)/statuses/.*#", $url, $matches); 
var_dump($matches[1]); 
+0

它顯示我NULL – EnexoOnoma 2012-02-08 23:16:18

+1

更改'([^ \ /])'爲'([^ \ /] +)' – webbiedave 2012-02-08 23:17:29

+0

這可能是,謝謝:) – Halcyon 2012-02-08 23:17:59

1
foreach ($twitter_xml2->channel->item as $key) { 
    $author = $key->{"guid"}; 
    list(,,,$username) = explode('/', $author); 
    echo"<li><h5>$username</h5></li>"; 
} 
+0

你可以發佈我的整個塊。順便說一句「用戶名」可能是任何東西 – EnexoOnoma 2012-02-08 23:13:12

+0

這將工作,如果用戶名是除「/」之外的任何東西,並在用戶名沒有改變之前進行斜線計數。 – 2012-02-08 23:21:09

1

您可以使用這個正則表達式(用於preg_match):~twitter\.com/([^/]+)/~

$match = array(); 
preg_match('~twitter\.com/([^/]+)/~', $url, $match); 
echo $match[1]; // list(,$userName) = $match; 

或更有效strpossubstr

$start = strpos($url, '/', 10); // say 10th character is after http:// and before .com/ 
$end = strpos($url, '/', $start+1); // This would be the end 
// Check both idexes 
$username = substr($url, $start, $end-$start); 
// you will maybe have to fix indexes +/-1