您知道反向路由已知问题。我正在使用CodeIgniter并尝试从正则表达式路由生成url。
我的示例路线:
$route['product-detail/([a-z]+)/('d+)'] = "catalog/product_view/$2";
或:
$route['product-detail/([a-z]+)/('d+)'] = array('catalog/product_view/$2', 'product-detail');
示例用法:
<a href="<?php echo route('product-detail' , array('category' => 'bikes', 'id' => 9)); ?>">Item Name</a>
预期产出:
<a href="/product-detail/bikes/9">Item Name</a>
我尝试了轻松反向路由,但它仅支持键而不是正则表达式字符串。
我怎样才能解决这个问题?
针对 reverseRoute
方法尝试此修复程序。更改此内容:
$route = $this->_reverseRoutes[$route_name];
foreach($args_keyval as $key => $val)
{
$route = str_replace("(:$key)", $val, $route);
}
return $route;
到这个 : 演示
$route = $this->_reverseRoutes[$route_name];
preg_match_all('/'(([^)]+)')/', $route, $matches);
if (isset($matches[1]) && is_array($matches[1])) {
$wildCardsAndRegex = $matches[1];
$index = 0;
foreach ($args_keyval as $key => $val)
{
if (isset($wildCardsAndRegex[$index])) {
if ($wildCardsAndRegex[$index][0] === ':') {
// for wildcard
$route = str_replace('(:'.$key.')', $val, $route);
} elseif (preg_match('/'.$wildCardsAndRegex[$index].'/', $val)) {
// for regex
$route = preg_replace('/'('.preg_quote($wildCardsAndRegex[$index], '''').'')/', $val, $route, 1);
}
}
$index++;
}
}
return $route;