Search code examples
phpurimatchfront-controller

PHP Matching URI to Pattern


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


Solution

  • 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';
    }