路由器::编译

时间:2013-10-28 10:09:36

标签: php kohana kohana-3

我正在尝试了解路由器在Kohana中的工作原理。

我走向方法编译并面临困难......

这一行是什么原因:

 $expression = preg_replace('#'.Route::REGEX_ESCAPE.'#', '\\\\$0', $uri);

方法编译:

public static function compile($uri, array $regex = NULL)
    {
        // The URI should be considered literal except for keys and optional parts
        // Escape everything preg_quote would escape except for : ( ) < >
        $expression = preg_replace('#'.Route::REGEX_ESCAPE.'#', '\\\\$0', $uri);

        if (strpos($expression, '(') !== FALSE)
        {
            // Make optional parts of the URI non-capturing and optional
            $expression = str_replace(array('(', ')'), array('(?:', ')?'), $expression);
        }

        // Insert default regex for keys
        $expression = str_replace(array('<', '>'), array('(?P<', '>'.Route::REGEX_SEGMENT.')'), $expression);

        if ($regex)
        {
            $search = $replace = array();
            foreach ($regex as $key => $value)
            {
                $search[]  = "<$key>".Route::REGEX_SEGMENT;
                $replace[] = "<$key>$value";
            }

            // Replace the default regex with the user-specified regex
            $expression = str_replace($search, $replace, $expression);
        }

        return '#^'.$expression.'$#uD';
    }



const REGEX_ESCAPE  = '[.\\+*?[^\\]${}=!|]';

可以提示单独的文章,以帮助我理解吗?

1 个答案:

答案 0 :(得分:2)

// What must be escaped in the route regex
const REGEX_ESCAPE  = '[.\\+*?[^\\]${}=!|]';

// The URI should be considered literal except for keys and optional parts
// Escape everything preg_quote would escape except for : ( ) < >
$expression = preg_replace('#'.Route::REGEX_ESCAPE.'#', '\\\\$0', $uri);

这部分代码意味着所有字符(圆形和尖括号除外)都将被转义。它有助于检测特定路线中的问号或点。

\\\\$0

要使用反斜杠,您需要在regexpr中复制它。

使用此preg_replace的结果的几个例子:

  

test =&gt;测试

     

test / =&gt;测试/

     

// test / =&gt; //测试/

     

//测试/! =&GT; //测试/#!

     

// test /!#$ =&gt; //测试/!#\ $

     

// test /!#$%^&amp; * aaa()bbb =&gt; !//测试/#\ $%\ ^&安培; * AAA()BBB