与 preg_match_all 匹配
我得到了这个正则表达式:
$val = "(123)(4)(56)";
$regex = "^(\((.*?)\))+$";
preg_match_all("/{$regex}/", $val, $matches);
任何人都可以告诉我为什么它只匹配最后一个数字(56)而不是单独的每组数字?
这是上面的正则表达式运行后 $matches 包含的内容:
array
0 =>
array
0 => string '(123)(4)(56)' (length=12)
1 =>
array
0 => string '(56)' (length=4)
2 =>
array
0 => string '56' (length=2)
I got this regex:
$val = "(123)(4)(56)";
$regex = "^(\((.*?)\))+$";
preg_match_all("/{$regex}/", $val, $matches);
Can anyone please tell me why this matches only the last number (56) and not each set of numbers individually?
This is what $matches contains after the above regex runs:
array
0 =>
array
0 => string '(123)(4)(56)' (length=12)
1 =>
array
0 => string '(56)' (length=4)
2 =>
array
0 => string '56' (length=2)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于 @develroot 已经回答了您想要使用
preg_match_all
的方式不起作用,因此它只会返回最后一个匹配组,而不是该组的所有捕获。这就是正则表达式的工作原理。目前我不知道如何在 PHP 中获取所有组的内容,我认为这是不可能的。可能不对,也可能会改变。但是,您可以针对您的情况解决这个问题,首先检查整个字符串是否与您的(重复)模式匹配,然后按该模式提取匹配项。将所有内容放在一个函数中,并且易于访问(演示):
As @develroot already has answered the way you want to use
preg_match_all
does not work, it will only return the last matching group, not all captures of that group. That's how regex works. At this point I don't know how to get all group catpures in PHP, I assume it's not possible. Might not be right, might change.However you can work around that for your case by first check if the whole string matches your (repeated) pattern and then extract matches by that pattern. Put it all within one function and it's easily accessible (Demo):