I’m interested in determining if named groups were used in the pattern passed to preg_match().
Imagine a scenario in which a list of regex patterns are iterated over and passed into preg_match(). Something like the following:
$trg = "123abc/4";
$patterns = array('/abc/', '/abc\/(\d+)/', '/abc\/(?P<id>\d+)/');
foreach ($patterns as $p) {
preg_match($p, $trg, $matches);
if (len($matches) > 0) {
// Do something interesting with the capture
}
}
If a match is found, then there will be at least one element in $matches. The two final patterns contain a capture, but $matches will be a two element array in the first case and
a three element array in the last.
I want to know, without grepping the pattern, if named groups were used. I need to know this because I want to pass the captured text on to other functions.
As you can imagine, the patterns will not be known until runtime, so I can’t simply look at the number of elements in the match.
Any ideas on how to tackle this?
Thanks for your time.
What about a custom is_assoc function? As PHP does not discriminate between lists and hashes, I’ve found it useful for a few other cases as well.
It lacks the “cleanliness” of already having a function for that purpose in PHP’s standard library (that I’m aware of), but the actual
ifstatement is still very compact and readable.I know your example probably only represents a small portion of your program, but it seems to me that all of the patterns are hand written by you and exist in the code, so you always know which ones will return named groups because you put the named groups in there. Couldn’t you just change
foreach ($patterns as $p)toforeach ($patterns as $i=>$p)and check the value of$iwhen a match is found?