Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

preg_match unconditionally return key for unmatched optional capture group

$pattern = "/^(?<animal>DOG|CAT)?(?<color>BLUE|RED)?$/i";
$str = "DOG";

preg_match($pattern, $str, $matches);
$matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);


// $str = "dog" returns [animal] => DOG

//$str = "dogBLUE" returns [animal] => dog and [color] => BLUE
print_r($matches);

I have an example http://sandbox.onlinephpfunctions.com/code/2428bc68adcf9929557d86dc1ae72552c3681b58 too

Both named capture groups are optional and so keys will only be returned if a match is found.

My Question

How can I unconditionally return keys for any of my possible named capture groups? Empty String ” would be great if it group ain’t found.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Input of "DOG" resulting in [animal] => 'DOG', [color] => '' is what I’m looking for.

I was hoping for a flag on preg_match to do this, but couldn’t find anything.

Update: I just want to avoid doing isset($matches[OPTIONAL_GROUP])

Thanks!

>Solution :

You can use andre at koethur dot de’s solution:

$pattern = "/^(?<animal>DOG|CAT)?(?<color>BLUE|RED)?$/i";
$str = "DOG";

if (preg_match($pattern, $str, $matches)) {
  $matches = array_merge(array('animal' => '', 'color' => ''), $matches);
  $matches = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
  print_r($matches);
}

See the PHP demo.
Output:

Array
(
    [animal] => DOG
    [color] => 
)

The idea is that you need to "assign a name to all subpatterns you are interested in, and merge $matches afterwards with an constant array containing some reasonable default values".

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading