3

I am working on a simple front controller, mainly for learning purposes.

I like the way Symfony does routing, having patterns in your map like this: /news/{category}/{id} and passing category and id variables to the controller. But my problem is -because of my incompetence of using RegEx - I don't know, how to match the patterns to the URI.

How should I match

/news/{category}/{id}

to

/news/tech/5784

Should I allow patterns like this: /news/* - where * matches everything? Or where the variables are mixed with some trash, like this /news/{category}_ex/14{id}?

Getting the variables and values are not much of the problem, but writing a regular expression for matching is.

Thank you for your help in advance

szab.kel
  • 2,356
  • 5
  • 40
  • 74
  • Are you trying to set up a route in Symphony, or are you trying to figure out how to make a regex match the URL you are working with. I'm not convinced that RegEx is actually what you need. – Joshua Kaiser Oct 29 '12 at 21:37
  • I am not working with Symfony. What I am trying to achieve: I got an URI from the user like http://site.com/news/tech/5784 and have a config file with a Map, the map containts the Patterns and its redirects ([0] array('pattern'=>'/news/{category}/{id}', 'controller'=>'NewsController:Index' [1] ...). I have to tell, if the requested URI is mapped and if is, save the uri variables and pass to the controller. – szab.kel Oct 29 '12 at 21:54
  • In that case pozs and anabhava both have suitable answers imo. The only question would be, what would you like to allow in the category and id fields? Will category always be a string? Will id always be an integer? These will be important when writing your regex. – Joshua Kaiser Oct 29 '12 at 22:04
  • I don"t understand where that regex came from. All I know is I have an uri and pattern. How can I convert the pattern to this regex form to match the uri? – szab.kel Oct 29 '12 at 22:06
  • Are you saying that I should use this form in my config file instead of the symfony way? {variable} – szab.kel Oct 29 '12 at 22:11

2 Answers2

4

The simplest would be to use (regex) named sub-patterns.

$regex = '#^/news/(?P<category>[a-z0-9]+)/(?P<id>[0-9]+)$#';
$path  = '/news/tech/5784';

if (preg_match($regex, $path, $matches))
{
    $matches['category'] === 'tech';
    $matches['id']       === '5784';
}
pozs
  • 34,608
  • 5
  • 57
  • 63
  • If I use sub-patterns in my configuration file (routes), it is ok, but isn't {varible} is better for readability ? – szab.kel Oct 29 '12 at 22:15
  • It is better only for readability - then you should use a framework with routing, which will (mostly) decode it to regexes like these – pozs Oct 29 '12 at 22:20
1

You're most likely looking for PHP Subpatterns

$str = '/news/tech/5784';
if (preg_match('~^/news/(?<category>[^/]+)/(?<id>[^/]+)~', $str, $match))
   echo $match['category'] . " - " . $match['id'] . "\n";

OUTPUT:

tech - 5784
anubhava
  • 761,203
  • 64
  • 569
  • 643