正则表达式匹配路径

时间:2014-06-13 09:24:40

标签: php regex

    $this->path = trim($path, '/');

    while (strpos($this->path, '//') !== false)
        $this->path = str_replace('//', '/', $this->path);

    $arraypath = ($this->path == '' ? [] : explode('/', $this->path));

    $c_arraypath = count($arraypath);
    $this->regex .= '/^';

    for ($i = 0; $i < $c_arraypath; $i++)
    {
        if ($arraypath[$i] == '*')
        {
            $this->regex .= '(?:\/(.+))?';
        }
        else
        {
            if ($i > 0)
            {
                $this->regex .= '\/';
            }

            if ($arraypath[$i] == '?')
            {
                $this->regex .= '([^\/]+)';
            }
            else
            {
                $this->regex .= preg_quote(strtolower($arraypath[$i]), '/');
            }
        }
    }
    $this->regex .= '$/i';

https://github.com/Manhim/Cervo/blob/dev-2.4.x/library/Cervo/Libraries/RouterPath.php(第79-112行)

这段代码的目的是保存一个正则表达式,可以用来匹配当前路径并获取路径中的参数。

规则是:

  • 字符串必须按原样匹配(不区分大小写)
  • ?标志恰好匹配1个参数
  • *符号匹配0个或多个参数
  • 只有参数必须匹配
  • 空路径必须仅匹配空路径
  • 如果只有*,则必须匹配所有内容
  • 最好不匹配任何起始或结束斜杠(/),但它会爆炸数组中的内容,并且可能会添加trim()最坏情况

EX:测试/?/?/ *

这将匹配Test / Arg1 / Arg2,Test / Arg1 / Arg2 / Arg3,......但它与Test / Arg1或Test不匹配。

不幸的是,它似乎并不适用于所有情况,我想为此提出更好的解决方案。

到目前为止,有两种方法可以解决这个问题:

  • 我可以在不使用正则表达式的情况下添加模式匹配代码
  • 我找到了使用正则表达式的解决方案

不幸的是,似乎正则表达式不是我的力量,我想知道这些事情是否已经存在(?),或者它是否在正则表达式中是可行的。

0 个答案:

没有答案