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

时间:2012-12-25 11:14:19

标签: php preg-match

我从PHP: Good solution for MVC routing function to parse requested views?获取了建议的解决方案,并将其添加到我们的内部指南中(再次感谢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:/ 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 Reverse Preg_match。但据我所知,这是一个负面的preg_match。或者我错了?

提前致谢。

1 个答案:

答案 0 :(得分:0)

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

例如

public function parseViewMapArrayKey($key) {

    return '#^'.str_replace([":reference:", ":string:"], ["\d+", ".+"], $key).'$#';

}