Why does preg_match return some empty elements?

I wrote regexp ^(?:([1-5])|([1-5]) .*|.* ([1-5])|.* ([1-5]) .*)$ To match either a single digit 1-5, or a digit divided by at least one space, the rest of the line. I tested it in online services, and the result is the figure itself. However, when using the code

 preg_match('/^(?:([1-5])|([1-5]) .*|.* ([1-5])|.* ([1-5]) .*)$/', 'order 12314124 5', $matches); 

I get this:

 Array ( [0] => order 12314124 5 [1] => [2] => [3] => 5 ) 

Element [0] is a complete match, which is good. I assumed that element [1] is 5, but it is empty, and there is another empty element. Why do these empty elements appear?

+6
source share
1 answer

If you used the regex at regex101.com, all non-participating (i.e. those that do not match) groups are hidden. You can enable them in the settings:

enter image description here

And you will see them:

enter image description here

A quick fix is โ€‹โ€‹to use the reset branch (?|...) instead of the non-capture group (?:...) and access to the value of $matches[1] :

 preg_match('/^(?|([1-5])|([1-5]) .*|.* ([1-5])|.* ([1-5]) .*)$/', 'order 12314124 5', $matches); print_r($matches[1]); // => 5 

Watch the IDEONE demo

+3
source

All Articles