我想获取城市列表,其中链接了每个城市名称并引用该城市的页面:
链接(在 View 脚本中创建)如下所示:
http://project.loc/catalog/Berlin (in the HTML source code url-encoded: Berlin)
http://project.loc/catalog/Erlangen (in the HTML source code url-encoded: Erlangen)
http://project.loc/catalog/Nürnberg (in the HTML source code url-encoded: N%C3%BCrnberg)
“Berlin”、“Erlangen”等有效,但如果城市名称包含德语特殊字符(ä
、ö
、ü
、Ä
、Ö
、Ü
或 ß
),例如“Nürnberg”,会出现 404 错误:
为什么?以及如何让它发挥作用?A 404 error occurred Page not found. The requested URL could not be matched by routing. No Exception available
提前致谢!
编辑:
我的路由器设置:
'router' => array(
'routes' => array(
'catalog' => array(
'type' => 'literal',
'options' => array(
'route' => '/catalog',
'defaults' => array(
'controller' => 'Catalog\Controller\Catalog',
'action' => 'list-cities',
),
),
'may_terminate' => true,
'child_routes' => array(
'city' => array(
'type' => 'segment',
'options' => array(
'route' => '/:city',
'constraints' => array(
'city' => '[a-zA-ZäöüÄÖÜß0-9_-]*',
),
'defaults' => array(
'controller' => 'Catalog\Controller\Catalog',
'action' => 'list-sports',
),
),
'may_terminate' => true,
'child_routes' => array(
// ...
),
),
),
),
),
),
最佳答案
您需要更改约束,可以使用匹配 UTF8 字符的正则表达式,如下所示:
'/[\p{L}]+/u'
注意/u 修饰符(unicode)。
编辑:
问题是resolved .
说明:
正则表达式路由将 URI 与 preg_match(...)
进行匹配(Zend\Mvc\Router\Http\Regex 的 116 或 118 行)。为了用“特殊字符”(128+)来处理字符串,必须传递模式修饰符 u
至preg_match(...)
。像这样:
$thisRegex = '/catalog/(?<city>[\p{L}]*)';
$regexStr = '(^' . $thisRegex . '$)u'; // <-- here
$path = '/catalog/Nürnberg';
$matches = array();
preg_match($regexStr, $path, $matches);
由于 RegEx Route 将 url 编码的字符串传递给 preg_match(...)
,需要进一步模式首先解码字符串:
$thisRegex = '/catalog/(?<city>[\p{L}]*)';
$regexStr = '(^' . $thisRegex . '$)u';
$path = rawurldecode('/catalog/N%C3%BCrnberg');
$matches = array();
preg_match($regexStr, $path, $matches);
正则表达式路由中没有提供这两个步骤,因此 preg_match(...)
得到像'/catalog/N%C3%BCrnberg'
这样的steing并尝试将其匹配到像 '/catalog/(?<city>[\\p{L}]*)/u'
这样的正则表达式
解决方案是使用自定义正则表达式路由。 Here就是一个例子。
关于带有德语特殊字符的 URI 在 Zend Framework 2 中不起作用(错误 404),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15634913/