Вопрос

I'm trying to understand how a router works in the Kohana.

I walked to the method compile and and faced with difficulties...

What makes this line here :

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

Method compile:

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  = '[.\\+*?[^\\]${}=!|]';

Can prompt separate article that will help me understand?

Это было полезно?

Решение

// 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);

This part of code means, that all chars (except round and angular brackets) will be escaped. It helps to detect question mark or dot in specific route.

\\\\$0

To use backslash you need to duplicate it in your regexpr.

Few examples of result using this preg_replace:

test => test

test/ => test/

//test/ => //test/

//test/! => //test/#!

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

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top