Matching with preg_match_all

前端 未结 1 1022
日久生厌
日久生厌 2021-01-16 19:14

I got this regex:

$val = \"(123)(4)(56)\";
$regex = \"^(\\((.*?)\\))+$\";
preg_match_all(\"/{$regex}/\", $val, $matches);

Can anyone please

相关标签:
1条回答
  • 2021-01-16 19:26

    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];
    }
    
    0 讨论(0)
提交回复
热议问题