I have a url for which i want to match a certain pattern
/events/display/id/featured
where
thus i end up with
Array (
[method] => display
[param] => Array ([0]=>id,[1]=>featured,[2]=>true /* if there was another path */)
)
so far i have
(?:/events/)/(?P<method>.*?)/(?P<parameter>.*?)([^/].*?)
But its not working out as expected.
What's wrong with the syntax?
P.S. no i don't want to use parse_url() or php defined function i need a regex
You can use this pattern:
<pre><?php
$subject = '/events/display/id1/param1/id2/param2/id3/param3';
$pattern = '~/events/(?<method>[^/]+)|\G(?!\A)/(?<id>[^/]+)/(?<param>[^/]+)~';
preg_match_all($pattern, $subject, $matches, PREG_SET_ORDER);
foreach($matches as $match) {
if (empty($match['method'])) {
$keyval[] = array('id'=>$match['id'], 'param'=>$match['param']);
} else {
$result['method'] = $match['method'];
}
}
if (isset($keyval)) $result['param'] = $keyval;
print_r($result);
pattern details:
~
/events/(?<method>[^/]+) # "events" followed by the method name
| # OR
\G # a contiguous match from the precedent
(?!\A) # not at the start of the string
/(?<id>[^/]+) # id
/(?<param>[^/]+) # param
~