0

您好,我有以下代码用于从 url 构建正则表达式。问题是当我没有将某些参数传递给方法时,我收到以下错误:

Warning: preg_match(): Empty regular expression on line 27

这是代码:

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;
    }
}

当我这样使用时:

$routeCollection->add('index', '/index.php/index/home/{name}', 'SiteName:Controller:Index', 'Home', ['name' => '(\w+)']);

它工作得很好,但是当我没有参数时,我只是通过了类似的东西:

$routeCollection->add('contact', '/index.php/contact/', 'SiteName:Controller:Contact', 'index');

我得到那个错误。无论如何,请帮我解决这个问题,因为我没有想法。

类的完整代码:

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;
    }
}
4

1 回答 1

3

当提供的没有时,您的buildRegex()方法返回。 NULL$uri{...}

NULL是一个空的正则表达式

解决方案?总是buildRegex()返回一个正则表达式!

于 2013-01-25T10:01:49.520 回答