Home » Php » php – Why does preg_match match multiple empty strings

php – Why does preg_match match multiple empty strings

Posted by: admin February 25, 2020 Leave a comment

Questions:

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

How to&Answers:

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

Answer:

You are receiving 3 empty elements because of your first three capture groups ([abc]+), ([012]+) and ([23]+) that did not match anything.

If you only want a single capture group, you could update your regex like this:

preg_match('/^([abc]+|[012]+|[23]+|[123]+)$/', '123', $match);

Which will give you:

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