doson1998 2010-09-28 19:36
浏览 152
已采纳

使用preg_match_all获取空数组结果,以获取不匹配的值

I am using preg_match_all to search for HashTag values in a Twitter Search response.

It works as I expected except for when the search results don't have any hash values in them. For some reason my $tags array still has values and I'm not sure why.

Is it because my RegEx is not correct, or is it a problem with preg_match_all?

Thanks

$tweet = "Microsoft Pivot got Runner-Up for Network Tech from The Wall Street Journal in 2010 Technology Innovation Awards  http://bit.ly/9pCbTh";

private function getHashTags($tweet){
    $tags = array();
    preg_match_all("/(#\w+)/", $tweet, $tags);

    return $tags;

}

results in:

Array ( [0] => Array ( ) [1] => Array ( ) )

Expected results:

Array();
  • 写回答

2条回答 默认 最新

  • dqyy38265 2010-09-28 19:42
    关注

    In default mode, preg_match_all returns an array of matches and submatches:

    PREG_PATTERN_ORDER
    Orders results so that $matches[0] is an array of full pattern matches, $matches[1] is an array of strings matched by the first parenthesized subpattern, and so on.

    So in this case the first array is the array of matches of the whole pattern and the second array is the array of matches of the first subpattern. And since there was no match found, both arrays are empty.

    If you want the other order, having each match in an array with its submatches, use PREG_SET_ORDER in the flags parameter:

    preg_match_all("/(#\w+)/", $tweet, $tags, PREG_SET_ORDER);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?