Matching with preg_match_all

十年热恋 提交于 2019-12-01 15:10:57

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];
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!