tags:

views:

100

answers:

2

I'm trying to get the controller, method and queries from a URL array. Something like this:

'home/news/[day]/[month]/[slug]/'

I need some regex which will give me the following:

Controller: home Method: News Arguments: day, month, slug

For the arguments, it'd be nice if I could somehow get the name inside the brackets so I can put them into an associative array in PHP. e.g: ("day"=>$day).

I'm really stuck with this, and tried looking at several PHP frameworks for guidance but nothing really accomplishes exactly what I want above, especially using regex.

I'd appreciate any tips / help / links! Thanks!

+3  A: 

If you're always going to have /:controller/:method/:args you might as well use explode:

$args = explode('/', $url);
$controllerName = array_shift($args);
$method = array_shift($args);

$controller = new $controllerName;
$response = $controller->$method($args);
rojoca
Hmmm, the problem is I would like to route my URL first, as I may also want /:controller/:item_id or something. Thinking about it, I think the best way to do this would be a combination of both regex and then the method above. Thanks very much for your reply.
Hanpan
+3  A: 
preg_match('{/home/news/(?<day>\d{1,2})/(?<month>\d{1,2})/(?<slug>[\w-]+)}',
           '/home/news/10/02/foo', 
           $matches);

$matches is now

array (
  0 => '/home/news/10/02/foo',
  'day' => '10',
  1 => '10',
  'month' => '02',
  2 => '02',
  'slug' => 'foo',
  3 => 'foo',
)
Øystein Riiser Gundersen
Genius, thank you.
Hanpan