need some help with some regex...

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

need some help with some regex...

Post 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]
User avatar
stereofrog
Forum Contributor
Posts: 386
Joined: Mon Dec 04, 2006 6:10 am

Post by stereofrog »

I'd rather use plain old explode()
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Yeah, I'm with stereofrog on this.
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Post by smudge »

Ahh... yes... I always make it too complicated. :D
Thanks for the advice. That works much better.
Post Reply