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

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败