用于标识 URL 的速记预处理匹配规则


Shorthand Preg Match Rule for Identifying URLs

假设我有数组:

[test1] = '/'
[test2] = '/foo'
[test3] = '/foo/*'
[test4] = '/bar/*'
[test5] = '/baz/*/bar'
这些规则需要

转换为什么有效的 grep 规则,以满足对输入执行preg_match函数(以规则作为模式),以便返回以下输入。 例如,规则需要封装在什么中,*需要用什么替换?

input          :   returned
/              :   test1
/foo           :   test2
/foo/bar       :   test3
/foobar        :   none
/bar           :   test4
/bar/foo       :   test4
/barfoo        :   none
/baz/foo/bar   :   test5
/baz//bar      :   none

替换为:

[^/]+

这表示非斜杠字符的非空字符串。 我正在根据你的最后一个例子做出假设(/baz//bar返回"无")。

当然,如果需要,请转义斜杠。

我认为从字符串中提取pathfilename可能会更好:

^('/(?:[^''/:*?"<>|]+'/)*)([^''/:*?"<>|]+)*$

第1组:path
第2组:filename

使用这些信息来查找表(例如哈希数组)

最后,我做到了:

<?php
$urlRule = str_replace('/', ''/', $urlRule);
$urlRule = '/^('.str_replace('*', ')(.*)(', $urlRule).')$/';
if (count(preg_grep($urlRule, array($url))) > 0) { ...

对于每个规则,但我确实需要包括

[test4] = '/bar'

为了实现

input          :   returned
/bar           :   test4