0

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.

Sumit Parakh
  • 1,098
  • 9
  • 19
  • @mickmackusa I want both matched elements and named group elements. For example, i have a sentence in which i am checking for occurrence of all vowels.:- $str = "The first regex has a named group (TAG), while the second one"; using this code:- preg_match_all('/(?P[aeiou])|(?P[AEIOU])/', $str, $vowelcase); It returns array of 5 elements, but i want only 3 , one - set of all matched elements, two - set of lower case vowel elements, three - set of upper case vowel elements. – Sumit Parakh May 25 '17 at 06:00
  • 1
    This will fix your output array: http://sandbox.onlinephpfunctions.com/code/270d1198be4cd29750a4bdd1d8258bf1781fa747 – mickmackusa May 25 '17 at 06:12
  • It worked like a charm. Thanks – Sumit Parakh May 25 '17 at 06:19

0 Answers0