I am learning Regular expressions and testing it with php and an online tool. When i run following php code, it creates an array with 2 elements which is correct and even make sense:-
preg_match('/(ab)+/', "ababab ab ab", $match); // captured group
print_r($match);
It returns:-
Array
(
[0] => ababab // matched word
[1] => ab // one captured group.
)
I've tested it here and it shows the same output(i.e., one match and one captured group):- https://regex101.com/r/5OYlY2/3
But When i change regular expression and convert it into a named group then preg_match returns 3 elements. I don't know why it is returning 3 elements because the same expression is giving only 2 output ( one match and one named group) here:- https://regex101.com/r/NdS6K7/3
code:-
// with named group
preg_match('/(?P<demo>ab)+/', "ababab ab ab", $match);
print_r($match); // returning array of 3 elements which it should not
Unexpected output:-
Array
(
[0] => ababab // one match, fine.
[demo] => ab // a named group, makes sense
[1] => ab // why on the earth this element was created?
)
why preg_match is returning 3 elements in case of named group regular expression? Why not it creates only 2 elements like this:-
Expected output:-
Array
(
[0] => ababab // one match, fine.
[demo] => ab // a named group, makes sense
)
Edit I want everything in the array except indexed elements, i.e., i want not only named elements but also matched elements.