繁体   English   中英

使用Regex将网址匹配到路由

[英]Matching a url to a route with Regex

我有一条这样的路线(YAML):

hello_route:
    path: /hello
    controller: HelloController
    action: helloAction

这可以正常工作并调用正确的控制器和操作,但是我很难匹配通配符。 例如,如果我想添加:

hello_route:
   path: /hello/{name}
   controller: HelloController
   action: helloAction

我尝试使用Regex,但是当您在浏览器中键入/hello/bob时,无论我对regex做什么,它总是说没有路由。 如何将regex用于URI /hello/bob仍与/hello/{name}匹配? 截至目前,它实际上在寻找/{name} ,它显然是!= /bob

到目前为止,我一直在使用此功能,因为我认为将{name}替换为*将使浏览器将其视为通配符。 但这是行不通的。

/**
 * Compiles routes
 *
 * @param  array $routes
 * @return string
 */
public function compileRoutes(array $routes)
{
    foreach($routes as $key => $val)
    {
        if($val['path'])
        {
            preg_match_all('/\{(\w+?)}/', $val['path'], $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

            foreach ($matches as $match)
            {
                if(isset($matches[0]) && isset($matches[1]))
                {
                    $matches[0] = '*';
                    $val['path'] = $matches[0];
                    $this->params[] = $matches[1]; 
                }
            }
        }
    }

    $this->routes = $routes;
}

这是@Tuga的回报

/
/test
/hello/{name} <- not being replaced

我不知道您想要什么,但是此正则表达式的语法错误

\{(\w+?)}

它必须是:

\{(\w+?)\}

或这个:

(\w+?)

暂无
暂无

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

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