preg_match_all how to get *all* combinations? Even overlapping ones

前端 未结 2 643
半阙折子戏
半阙折子戏 2021-01-18 20:39

Is there a way in the PHP regex functions to get all possible matches of a regex even if those matches overlap?

e.g. Get all the 3 digit substrings \'/[\\d

相关标签:
2条回答
  • 2021-01-18 20:43

    Look-ahead assertions to the rescue!

    preg_match_all('/(?=(\d{3}))/', $str, $matches);
    print_r($matches[1]);
    

    It basically captures whatever the look-ahead assertion is matching. Since the assertion is zero width, $matches[0] will only contain empty strings, but $matches[1] will contain the expected captured patterns.

    0 讨论(0)
  • 2021-01-18 20:54

    This may not be ideal, but at least it's something.

    It looks like you could use a positive lookahead and PREG_OFFSET_CAPTURE to get all the string indexes for where a 3-digit number exists

    $str = "123456";
    
    preg_match_all("/\d(?=\d{2})/", $str, $matches, PREG_OFFSET_CAPTURE);
    
    $numbers = array_map(function($m) use($str){
      return substr($str, $m[1], 3);
    }, $matches[0]);
    
    print_r($numbers);
    

    Output

    Array
    (
        [0] => 123
        [1] => 234
        [2] => 345
        [3] => 456
    )
    
    0 讨论(0)
提交回复
热议问题