preg_match - PHP:搜索调用preg_match反向顺序的解决方案


preg match - PHP: Solution for reverse order of search invoking preg_match

我采取了建议的解决方案从PHP: MVC路由功能解析请求视图的好解决方案?并将其调整为我们的内部指导方针(再次感谢Supericy)。

我现在有以下代码:

public function parseRequestedView($url) {
    $this->view_requested = explode('/', trim($url, '/'));
    // Format: [0] viewpoint, [1] child, [2] action (default: show), [3] reference
    $this->view_map = array(
        $this->parseViewMapArrayKey('device/:reference:/configurations') => array(0,  2, -1,  1),
        $this->parseViewMapArrayKey('device/:reference:')                => array(0, -1, -1,  1)
    );
    foreach ($this->view_map as $this->view_map_transitory => $this->view_map_indices) {
        if (preg_match($this->view_map_transitory, $url)) {
            foreach ($this->view_map_indices as $this->view_index) {
                $this->view_resources[] = $this->view_index > -1 ? $this->view_requested[$this->view_index] : null;
            }
            return $this->view_resources;
        }
    }
    return false;
}
public function parseViewMapArrayKey($key) {
    return '#'.str_replace([":reference:", ":string:"], ["'d+", ".+"], $key).'#';
}

一切正常,除了一个小问题:

当我切换键"device/:reference:"answers"device/:reference:/configurations",然后调用device/:reference:/configurations的视图时,我只得到device/:reference的结果。

例如,http://ww.foo.com/device/123456/configurations将输出:

Array
(
    [0] => device
    [1] => 
    [2] => 
    [3] => 123456
)

这是http://ww.foo.com/device/123456的结果。当我将密钥更改回原来的顺序时,一切都像它应该的那样:

Array
(
    [0] => device
    [1] => configurations
    [2] => 
    [3] => 123456
)

当我切换键时,如何反转搜索顺序或使函数输出正确的结果?

我发现这个PHP反向Preg_match。但据我所知,这是一个负的preg_match。还是我错了?

好吧,也许这是一个愚蠢的答案,但也许你可以确保你的正则表达式以^开始,以$结束?

例如

public function parseViewMapArrayKey($key) {
    return '#^'.str_replace([":reference:", ":string:"], ["'d+", ".+"], $key).'$#';
}