[英]php url routing
Hello i have the following code which i use to build a regex from url. 您好,我有以下代码,我使用这些代码从url构建正则表达式。 the problem is when i don't pass certain params to the method i get the following error: 问题是当我不将某些参数传递给方法时,出现以下错误:
Warning: preg_match(): Empty regular expression on line 27
This is the code: 这是代码:
public function buildRegex($uri, array $params)
{
// Find {params} in URI
if(preg_match_all('/\{(?:[^\}]+)\}/', $uri, $this->matches, PREG_SET_ORDER))
{
foreach($this->matches as $isMatch)
{
// Swap {param} with a placeholder
$this->uri = str_replace($isMatch, "%s", $uri);
}
// Build final Regex
$this->finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';
$this->finalRegex = vsprintf($this->finalRegex, $params);
return $this->finalRegex;
}
}
when i use like this: 当我这样使用时:
$routeCollection->add('index', '/index.php/index/home/{name}', 'SiteName:Controller:Index', 'Home', ['name' => '(\w+)']);
it works just fine but when i don't have params and i just pass something like: 它工作正常,但是当我没有参数并且我只是通过类似的东西:
$routeCollection->add('contact', '/index.php/contact/', 'SiteName:Controller:Contact', 'index');
i get that error. 我得到那个错误。 Anyway around to give me a hand fixing this problem because i'm out of ideas. 无论如何都可以帮我解决这个问题,因为我没有主意。
The Entire Code of the class: 该课程的完整代码:
class RouterCollection
{
public $routeCollection = [];
public function add($name, $pattern, $controller, $action = null, array $params = [])
{
if(!isset($this->routeCollection[$name]))
$this->routeCollection[$name] =
[
'pattern' => $pattern,
'controller' => $controller,
'action' => $action,
'params' => $params,
];
}
public function findMatch($url)
{
foreach($this->routeCollection as $routeMap)
{
$this->regex = $this->buildRegex($routeMap['pattern'], $routeMap['params']);
// Let's test the route.
if(preg_match($this->regex, $url))
{
return ['controller' => $routeMap['controller'], 'action' => $routeMap['action']];
}
else
{
return ['controller' => $this->routeCollection['404']['controller'], 'action' => $this->routeCollection['404']['action']];
}
}
}
public function buildRegex($uri, array $params)
{
// Find {params} in URI
if(preg_match_all('/\{(?:[^\}]+)\}/', $uri, $this->matches, PREG_SET_ORDER))
{
foreach($this->matches as $isMatch)
{
// Swap {param} with a placeholder
$this->uri = str_replace($isMatch, "%s", $uri);
}
// Build final Regex
$this->finalRegex = '/^' . preg_quote($this->uri, '/') . '$/';
$this->finalRegex = vsprintf($this->finalRegex, $params);
return $this->finalRegex;
}
}
public function getCollection()
{
return $this->routeCollection;
}
}
Your buildRegex()
method returns NULL
when the provided $uri
has no {...}
in it. 当提供的$uri
中没有{...}
时,您的buildRegex()
方法将返回NULL
。
NULL
is an empty regex . NULL
是一个空的正则表达式 。
The solution? 解决方案? Make buildRegex()
always return a regex! 使buildRegex()
始终返回正则表达式!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.