0

我试图了解路由器在 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  = '[.\\+*?[^\\]${}=!|]';

能否提示单独的文章,帮助我理解?

4

1 回答 1

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

要使用反斜杠,您需要在您的正则表达式中复制它。

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

测试 => 测试

测试/ => 测试/

//测试/ => //测试/

//测试/!=> //测试/#!

//test/!#$ => //test/!#\$

//test/!#$%^&*aaa()bbb => //test/!#\$%\^&*aaa()bbb

于 2013-10-28T10:23:55.597 回答