【问题标题】:Reverse routing from regex从正则表达式反向路由
【发布时间】:2014-11-14 11:45:57
【问题描述】:

您知道反向路由已知问题。我正在使用 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,但它只支持键而不支持正则表达式字符串。

我该如何解决这个问题?

【问题讨论】:

  • route() 函数是股票代码点火器的一部分吗?
  • @Brewal 不,只是一个将路由转换为 url 的示例不存在的函数。
  • 确实,您链接的子类似乎没有完成。它部分支持正则表达式。您可能看不到“没有为 'product-detail' 找到反向路由”错误吗?
  • 我想使用 $route['product-detail/([a-z]+)/(\d+)'] 而不是 $route['product-detail/(:category)/(:id)']
  • 我明白...我正在修复您链接的课程

标签: php regex codeigniter routing url-routing


【解决方案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;

【讨论】:

  • 很好的答案!非常感谢。
  • 我堆积了可选的正则表达式。 $route['products(/[a-z]+)?'] = array('products$1', 'products'); 我如何传递可选参数?如果参数存在,url 应该是products/bikes,如果参数不存在,url 应该只有products
猜你喜欢
  • 1970-01-01
  • 2020-10-10
  • 2019-01-01
  • 2014-04-14
  • 2012-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多