So this is the problem, Im using preg_match, to match current URI from browser, with the ones defined in my router.php config file. Im building Router/Dispatcher similar to Django.
What I want is that preg_match() captures only named regexs in $matches variable.
So If I have regexs like this:
^(?<param1>[a-z]+(?:\-[a-z]+)*)\.domain\.com\/[a-z]+(?:\/)?(?<param2>[a-z]+)?\/?$
Rubural link: CLICK
When I compare current URI with this regexs it matches, but $matches variable returns this:
array ( 0 => 'sub.domain.com/page/pageurl/', 'param1' => 'sub', 1 => 'sub', 'param2' => 'pageurl', 2 => 'pageurl', )
Is it possible to tell preg_match() to return only named matches, and exclude those numeric one, what I would like to get is Associative Array 🙂
I could use foreach() and loop through $match and then inside check if its numeric or not… is there any better way?
Thanks
I can’t find anything in the PHP manuals about named subpatterns in the first place, but I’m going to take an educated guess and say that you can’t prevent the numeric keys in the resulting array.
The ground for this guess is that key
0always contains the full match, and there’s no way of naming that match.If you want to strip out numeric indices, the best way would probably be a
foreachloop.