与 preg_match_all 匹配

发布于 2024-11-19 08:58:28 字数 444 浏览 2 评论 0原文

我得到了这个正则表达式:

$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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

握住我的手 2024-11-26 08:58:29

由于 @develroot 已经回答了您想要使用 preg_match_all 的方式不起作用,因此它只会返回最后一个匹配组,而不是该组的所有捕获。这就是正则表达式的工作原理。目前我不知道如何在 PHP 中获取所有组的内容,我认为这是不可能的。可能不对,也可能会改变。

但是,您可以针对您的情况解决这个问题,首先检查整个字符串是否与您的(重复)模式匹配,然后按该模式提取匹配项。将所有内容放在一个函数中,并且易于访问(演示):

$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];
}

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

$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];
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文