与 preg_match_all 匹配 [英] Matching with preg_match_all
问题描述
我得到了这个正则表达式:
I got this regex:
$val = "(123)(4)(56)";
$regex = "^(\((.*?)\))+$";
preg_match_all("/{$regex}/", $val, $matches);
谁能告诉我为什么这只匹配最后一个数字 (56) 而不是每组数字单独匹配?
Can anyone please tell me why this matches only the last number (56) and not each set of numbers individually?
这是 $matches 在上述正则表达式运行后包含的内容:
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)
推荐答案
由于@develroot 已经回答了你想使用的方式 preg_match_all
不起作用,它只会返回最后匹配的组,并非该组的所有捕获.这就是正则表达式的工作原理.在这一点上,我不知道如何在 PHP 中获取所有组 catpures,我认为这是不可能的.可能不对,可能会改变.
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.
但是,您可以通过首先检查整个字符串是否与您的(重复)模式匹配,然后通过该模式提取匹配项来解决您的情况.将其全部放在一个函数中,并且易于访问(Demo):
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):
$tests = explode(',', '(123)(4)(56),(56),56');
$result = array_map('extract_numbers', $tests);
print_r(array_combine($tests, $result));
function extract_numbers($subject) {
$number = '\((.*?)\)';
$pattern = "~^({$number})+$~";
if (!preg_match($pattern, $subject)) return array();
$pattern = "~{$number}~";
$r = preg_match_all($pattern, $subject, $matches);
return $matches[1];
}
这篇关于与 preg_match_all 匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!