简体   繁体   English

正则表达式解决方案以查找正则表达式模式并对其进行解析。

[英]Regex solution to find a regex pattern and parse it.

I am trying to write a simple router for PHP. 我正在尝试为PHP写一个简单的路由器。 And I am facing some problem. 我正面临一些问题。 Example of the routes are as follows. 路线示例如下。

$route = []
$route['index']     = "/"; 
$route['home']      = "/home";
$route['blog']      = "/blog/[a-z]";
$route['article']   = "/article/id/[\d+]/title/[\w+]";

Now if we take the last example, I would like the regex only to look for patterns such as [\\d+] and [\\w+] that is it. 现在,如果我们以最后一个示例为例,我希望正则表达式仅查找诸如[\\d+][\\w+]之类的模式。 I will use explode() to actually cross check if URL contains /blog/ , /id/ and /title/ . 我将使用explode()来实际交叉检查URL是否包含/blog//id//title/ I don't want regex's help with that, but only to detect the patterns and match it. 我不希望正则表达式对此有所帮助,而只是检测模式并进行匹配。

for example. 例如。 If a given $URL was dev.test/blog/id/11/title/politics 如果给定的$URLdev.test/blog/id/11/title/politics

I would need some like: preg_match($route['url'], $URL) 我需要一些像: preg_match($route['url'], $URL)

So, now the preg_match() function knows, that after "/article/id/ there is a pattern asking only for a digit to occur, then if the digit is found it will continue parsing, or else it will show fail or 0 . 因此,现在preg_match()函数知道,在"/article/id/有一个模式仅要求出现一个数字,然后,如果找到该数字,它将继续解析,否则将显示fail或0

I don't know much about regex to handle this complex problem. 对于处理这个复杂问题,我对正则表达式了解不多。

Your question is a little unclear, but if you want only to capture the [\\d+] or [\\w+] parts of the target string, you should consider using brackets to capture sub-matches, and the (?:xxx) non-capturing match, which checks for the pattern but does not add it to the array, something like: 您的问题尚不清楚,但是如果您只想捕获目标字符串的[\\ d +]或[\\ w +]部分,则应考虑使用方括号来捕获子匹配项,而(?:xxx)非捕获匹配项,它检查模式,但不将其添加到数组中,例如:

  $route['article']   = "(?:\/article\/id\/)([\d+])(?:\/title\/)([\w+])";

This will add the matched [\\d+] and [\\w+] to your matches array only. 这只会将匹配的[\\ d +]和[\\ w +]添加到您的matchs数组中。 You'll find them like so: 您会发现它们是这样的:

  $matches[0][0] and matches[1][0].

See http://www.regular-expressions.info/tutorial.html for an outstanding tutorial on regexes, by the way. 顺便说一下,有关正则表达式的出色教程,请参见http://www.regular-expressions.info/tutorial.html

If you aren't sure of the values of 'article', 'id', and 'title' in advance, then you will probably at least need to be sure of the number of directories given in the url. 如果您事先不确定'article','id'和'title'的值,则可能至少需要确保url中给定的目录数。 That means as long as you know the position of the [\\d+] and [\\w+] entries, you could use 这意味着只要您知道[\\ d +]和[\\ w +]条目的位置,就可以使用

    $route['article'] = "(?:\/[\w+]\/[w+]\/)([\d+])(?:\/[\w+]\/)([\w+])"

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

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