Search code examples
phpregexpreg-matchpreg-match-all

PHP preg_match_all does not match everything


Consider the following code snippet:

$example = "DELIM1test1DELIM2test2DELIM1test3DELIM2test4"; // and so on

preg_match_all('/DELIM1(.*?)DELIM2(.*?)/', $example, $matches);

$matches array becomes:

array:3 [
  0 => array:2 [
    0 => "DELIM1test1DELIM2"
    1 => "DELIM1test3DELIM2"
  ]
  1 => array:2 [
    0 => "test1"
    1 => "test3"
  ]
  2 => array:2 [
    0 => ""
    1 => ""
  ]
]

As you can see, it fails to get test2 and test4. Any reason why that happens and what could be a possible solution? Thank you.


Solution

  • .*? is non-greedy; if you have no constraint after it, it will match the minimum necessary: zero characters. You need a constraint after it to force it to match more than trivially. For example:

    /DELIM1(.*?)DELIM2(.*?)(?=DELIM1|$)/