need some help with some regex...
Posted: Sat Aug 18, 2007 5:07 pm
Ok, title's bad, but i couldn't think of a better one.
I have a script that is supposed to take a url and parse it into sections for a framework I'm working on.
The url will have the form /controller/action/param/param...
there is one controller, 0 or 1 actions, and any number of params, including no params.
Preferably I would like the output to be an associative array like array('controller'=>$matches[1], 'action'=>$matches[2], 'params'=>$matches[3])
So far I have cobbled together a regex that I think is what I need, but I'm not sure:
If i understand correctly (and I probably don't), it should work like this:
\/+(.*) matches /controller into $matches[1]
(?: is a non capturing sub-group, so
(?:\/+(.*)(\/+(.*))*)? should match anything past the controller (0 or 1 times) into $matches[2] and /param (* times) into $matches[3]
I have a script that is supposed to take a url and parse it into sections for a framework I'm working on.
The url will have the form /controller/action/param/param...
there is one controller, 0 or 1 actions, and any number of params, including no params.
Preferably I would like the output to be an associative array like array('controller'=>$matches[1], 'action'=>$matches[2], 'params'=>$matches[3])
So far I have cobbled together a regex that I think is what I need, but I'm not sure:
Code: Select all
function decodeRoute($url){
$matches=array();
preg_match("/\/+(.*)(?:\/+(.*)(\/+(.*))*)?/i",$url,$matches);
return array(
'controller'=>$matches[1],
...
);
}\/+(.*) matches /controller into $matches[1]
(?: is a non capturing sub-group, so
(?:\/+(.*)(\/+(.*))*)? should match anything past the controller (0 or 1 times) into $matches[2] and /param (* times) into $matches[3]