简体   繁体   English

PHP将URI匹配到模式

[英]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. 我喜欢Symfony做路由的方式,在你的地图中有这样的模式: /news/{category}/{id}并将类别和id变量传递给控制器​​。 But my problem is -because of my incompetence of using RegEx - I don't know, how to match the patterns to the URI. 但我的问题是 - 因为我无法使用RegEx - 我不知道,如何将模式匹配到URI。

How should I match 我该怎么配?

/news/{category}/{id}

to

/news/tech/5784

Should I allow patterns like this: /news/* - where * matches everything? 我应该允许这样的模式: /news/* - 其中*匹配所有内容? Or where the variables are mixed with some trash, like this /news/{category}_ex/14{id} ? 或者变量与某些垃圾混合在一起,例如/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 您最有可能寻找PHP子模式

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

OUTPUT: OUTPUT:

tech - 5784

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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