对于不匹配的值,使用 preg_match_all 获取空数组结果
我正在使用 preg_match_all 在 Twitter 搜索响应中搜索 HashTag 值。
它按我的预期工作,除非搜索结果中没有任何哈希值。由于某种原因,我的 $tags 数组仍然具有值,但我不确定为什么。
是因为我的RegEx不正确,还是preg_match_all有问题?
感谢
$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;
}
结果:
Array ( [0] => Array ( ) [1] => Array ( ) )
预期结果:
Array();
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();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在默认模式下,
preg_match_all
返回匹配项和子匹配项的数组:因此,在这种情况下,第一个数组是整个模式的匹配数组,第二个数组是第一个子模式的匹配数组。由于没有找到匹配项,因此两个数组都是空的。
如果您想要其他顺序,将每个匹配项及其子匹配项放在一个数组中,请在 flags 参数中使用
PREG_SET_ORDER
:In default mode,
preg_match_all
returns an array of matches and submatches: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_OFFSET_CAPTURE
作为标志参数传递,否则您始终会从 preg_match_all 获得多维数组。在这种情况下,您实际上应该为不匹配任何内容的表达式获取一个空数组。You get two empty arrays because you are matching an expression and a subexpression. Your expected results are actually the error here. Check the manual, specifically the description of the default behavior when no flags are passed in the fourth argument:
You always get a multi-dimensional array from preg_match_all unless you pass
PREG_OFFSET_CAPTURE
as the flag argument. In this case, you should actually get an empty array for an expression that doesn't match anything.