URL routing and regular expressions

I’m not a regex ninja, but how’s this for you?
/\/(?<area>[\w\d\-_]+)?(\/(?<controller>[\w\d\-_]+))?(\/(?<action>[\w\d\-_]+))?(\/(?<param1>[\w\d\-_]+))?(\/(?<param2>[\w\d\-_]+))?/

I tried it against all of these examples and it looks like it’s working to me:

  • /
  • /site
  • /admin
  • /site/account
  • /admin/user
  • /site/pm/create
  • /admin/user/create
  • /site/pm/read/1
  • /admin/user/edit/2
  • /site/vm/view/1/2
  • /site/pm/page-5
  • /admin/user/page-6

If you do preg_match($pattern, $route, $matches); you should find that you have a $matches array that has named groups, so you would be able to check for $matches['area'], $matches['controller'], $matches['action'], $matches['param1'] and $matches['param2']