How to set a (UTF8) modifier for RegEx of a RegEx Route in Zend Framework 2?

后端 未结 2 1914
Happy的楠姐
Happy的楠姐 2020-12-06 14:34

I\'m having troubles with (german) special characters in URIs and want to try to resolve it with a RegEx Route and a PCRE pattern modifier for UTF-8 u.

2条回答
  •  北海茫月
    2020-12-06 15:15

    Since I already had this open here's a handler that solves the problem.

    getUri();
            // path decoded before match
            $path = rawurldecode($uri->getPath());
    
            // regex with u modifier    
            if ($pathOffset !== null) {
                $result = preg_match('(\G' . $this->regex . ')u', $path, $matches, null, $pathOffset);
            } else {
                $result = preg_match('(^' . $this->regex . '$)u', $path, $matches);
            }
    
            if (!$result) {
                return null;
            }
    
            $matchedLength = strlen($matches[0]);
    
            foreach ($matches as $key => $value) {
                if (is_numeric($key) || is_int($key) || $value === '') {
                    unset($matches[$key]);
                } else {
                    $matches[$key] = $value;
                }
            }
    
            return new RouteMatch(array_merge($this->defaults, $matches), $matchedLength);
        }
    }
    

    Assuming you place the file in Application/Mvc/Router/Http/UnicodeRegex your route definition should look like this

    'router' => array(
        'routes' => array(
            // ...
            'city' => array(
                'type'  => 'Application\Mvc\Router\Http\UnicodeRegex',
                'options' => array(
                    'regex' => '/catalog/(?[\p{L}]+)',
                    // or if you prefer, your original regex should work too
                    // 'regex' => '/catalog/(?[a-zA-Z0-9_-äöüÄÖÜß]*)',
                    'defaults' => array(
                        'controller' => 'Catalog\Controller\Catalog',
                        'action'     => 'list-sports',
                    ),
                    'spec'  => '/catalog/%city%',
                ),
                'may_terminate' => true,
            ),
        ),
    ),
    

提交回复
热议问题