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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度