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 0
always 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 foreach
loop.
Try this code:
$namedFields = array_filter(array_keys($matches), "is_string");
$row = array_intersect_key(
$matches, // 4. "filling" flipped key array with actual values
array_flip( // 3. fliping array
array_filter( // 2. keeping string keys
array_keys($matches), // 1. taking keys
"is_string")));
also with php5.6 you could use array_filter
$row = array_filter(
$matches,
'is_string',
ARRAY_FILTER_USE_KEY
);