使用PHP只获取字符串的一部分

时间:2012-02-08 23:03:28

标签: php twitter

我使用以下代码

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

它让我http://twitter.com/USERNAME/statuses/167382363782206976

我的问题是如何只获取用户名?

用户名可以是任何内容

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

答案 2 :(得分: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