Preg_match_all how to get * all * combinations? Even overlapping

Is there a way in PHP regular expressions to get all possible regular expression matches, even if matches match?

eg. Get all 3-digit substrings '/ [\ d] {3} /' ...

You can expect:

"123456" => ['123', '234', '345', '456']

But preg_match_all () only returns

['123', '456']

This is due to the fact that it starts searching again after the substring substring (as indicated in the documentation):

"After the first match is found, subsequent searches continue from the end of the last match."

Is there any way around this without writing a custom parser?

+4
2

!

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

, . , $matches[0] , $matches[1] .

+6

, , , -.

, lookahead PREG_OFFSET_CAPTURE, , 3-

$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);

Array
(
    [0] => 123
    [1] => 234
    [2] => 345
    [3] => 456
)
+2

Source: https://habr.com/ru/post/1532124/


All Articles