简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM