从正则表达式反向路由

时间:2014-11-14 11:45:58

标签: php regex codeigniter routing url-routing

您知道反向路由已知问题。我正在使用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>

我尝试了Easy Reverse Routing,但它只支持非正则字符串的键。

我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:1)

reverseRoute方法尝试此修复程序。改变这个:

$route = $this->_reverseRoutes[$route_name];

foreach($args_keyval as $key => $val)
{
    $route = str_replace("(:$key)", $val, $route);
}

return $route;

指向: demo

$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;