Regular Expression Name Based Matches

Normally when i write regular expressions with for instance PHP´s preg_match. I will use the standard $matches array to catch the result of pattern matches. This array has a normal numeric index for each match found. And looks something like

Normal preg_match
$matches = array();
preg_match("/^Get(.+)Repository$/", "GetFooBarRepository", $matches);
var_dump($matches);
array(2) {
  [0] => string(19) "GetFooBarRepository"
  [1] => string(6) "FooBar"
}

And there is nothing wrong with that. Except for the fact that numeric indexes are not always easy to work with. And it does not look all that clean in the code itself. SO last week my LD pointed out the fact that the likes using name based indexes for the matched patterns. And this is pretty sweet. I have seen it before but never bothered to adopt it myself. And the result looks like

Name based index preg_match
$matches = array();
preg_match("/^Get(?<repositoryname>.+)Repository$/", "GetFooBarRepository", $matches);
var_dump($matches);
array(3) {
  [0] => string(19) "GetFooBarRepository"
  'repositoryName' => string(6) "FooBar"
  [1] => string(6) "FooBar"
}

And i have to say. It looks a lot cleaner. So i added this to my bag of tricks. And will be using it from now on.

comments powered by Disqus