[英]How to set a (UTF8) modifier for RegEx of a RegEx Route in Zend Framework 2?
我在URI中遇到了(德语)特殊字符的麻烦,想要尝试使用RegEx Route和UTF-8 u
的PCRE模式修饰符来解决它。
'router' => array(
'routes' => array(
// ...
'city' => array(
'type' => 'regex',
'options' => array(
'regex' => '/catalog/(?<city>[a-zA-Z0-9_-äöüÄÖÜß]*)\/u',
'defaults' => array(
'controller' => 'Catalog\Controller\Catalog',
'action' => 'list-sports',
),
'spec' => '/catalog/%city%',
),
'may_terminate' => true,
),
),
),
但是当我设置它时,路径就会停止工作(错误404) - 既不是URI也不是没有特殊字符的URI。
如何正确设置修改器?
因为我已经在这里打开了这个解决问题的处理程序。
<?php
namespace Application\Mvc\Router\Http;
use Zend\Mvc\Router\Http\Regex;
use Zend\Mvc\Router\Http\RouteMatch;
use Zend\Stdlib\RequestInterface as Request;
class UnicodeRegex extends Regex
{
/**
* match(): defined by RouteInterface interface.
*
* @param Request $request
* @param integer $pathOffset
* @return RouteMatch
*/
public function match(Request $request, $pathOffset = null)
{
if (!method_exists($request, 'getUri')) {
return null;
}
$uri = $request->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);
}
}
假设您将文件放在Application/Mvc/Router/Http/UnicodeRegex
您的路由定义应该如下所示
'router' => array(
'routes' => array(
// ...
'city' => array(
'type' => 'Application\Mvc\Router\Http\UnicodeRegex',
'options' => array(
'regex' => '/catalog/(?<city>[\p{L}]+)',
// or if you prefer, your original regex should work too
// 'regex' => '/catalog/(?<city>[a-zA-Z0-9_-äöüÄÖÜß]*)',
'defaults' => array(
'controller' => 'Catalog\Controller\Catalog',
'action' => 'list-sports',
),
'spec' => '/catalog/%city%',
),
'may_terminate' => true,
),
),
),
好,
我猜你可以像许多其他人一样容易解决这个问题。 所以看看其中一些:
使用以下修饰符,如
\\\\s
, \\\\p{L}
和\\\\u\u003c/code>来帮助您。
我希望它能解决! 祝好运。
编辑
看我自己的测试:
<?php
$toss_the_dice = utf8_decode ("etc/catalog/Nürnberg");
preg_match ('/\/catalog\/([\\s\\p{L}]*)/m', $toss_the_dice, $dice);
echo utf8_encode ($dice[1]);
// Now it prints
// Nürnberg
?>
你能意识到吗?
编辑2
对你来说可能更好!
<?php
$toss_the_dice = "etc/catalog/Nürnberg";
preg_match ('/\/catalog\/([\\s\\p{L}]*)/u', $toss_the_dice, $dice);
echo $dice[1];
// Now it also prints
// Nürnberg
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.