Page 1 of 1

need some help with some regex...

Posted: Sat Aug 18, 2007 5:07 pm
by smudge
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:

Code: Select all

function decodeRoute($url){
  $matches=array();
  preg_match("/\/+(.*)(?:\/+(.*)(\/+(.*))*)?/i",$url,$matches);
  return array(
    'controller'=>$matches[1],
    ...
  );
}
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]

Posted: Sat Aug 18, 2007 6:17 pm
by stereofrog
I'd rather use plain old explode()

Posted: Sat Aug 18, 2007 7:31 pm
by feyd
Yeah, I'm with stereofrog on this.

Posted: Sat Aug 18, 2007 7:48 pm
by smudge
Ahh... yes... I always make it too complicated. :D
Thanks for the advice. That works much better.