Search code examples
phpregexpreg-match

Why does preg_match match multiple empty strings


Why does the following regex:

$regex = '^([abc]+)$|^([012]+)$|^([23]+)$|^([123]+)$';
$toMatch = '123';
preg_match('/'.$regex.'/', $toMatch, $matches);

result in this result:

array(5) {
  [0]=>
  string(3) "123"
  [1]=>
  string(0) ""
  [2]=>
  string(0) ""
  [3]=>
  string(0) ""
  [4]=>
  string(3) "123"
}

Why are the elements 1,2 and 3 empty strings while they didn't match anything? How come there are an "empty" matches?

thanks in advance


Solution

  • You attempted to capture 4 different things with the () syntax. Therefore, there will be 4 different elements in the $matches array. Only the last capture will match the string 123 (^[123]+$).

    See the documentation