【问题标题】:Routing in Codeigniter with colon in URL :在 URL 中使用冒号在 Codeigniter 中路由:
【发布时间】:2015-03-05 12:37:21
【问题描述】:

这条路线

$route['api2/(:any)'] = "api2/api2/$1/";

匹配这些网址:

/api2/pictures/alpha_string
/api2/pictures/picture_id:alpha_string

但不是这个:

/api2/pictures/picture_id:55

不同之处在于我在“:”之后使用数字。

如何使它与最后一个 URL 匹配?

谢谢

【问题讨论】:

  • 你为什么使用冒号?
  • 为什么你的路线中有两个api2.. 还有为什么不直接放$1 而不是$1,$2,$3..?
  • @CodeGodie:删除了 $1, $2 ...我在测试时忘记了它们。 api2/api2 反映了站点的内部结构,对于这个例子并不重要。
  • @Craig:冒号是允许的 URI 字符。
  • 在URL中是允许的,但不作为段分隔符传递,是吗?

标签: php codeigniter routing


【解决方案1】:

如果您想在 codeigniter url 中使用冒号 (:) 字符,您可以从以下说明中扩展 CI_RouterCI_URI 类:

首先,在“application/core”文件夹中新建文件“MY_Router.php”:

<?php defined('BASEPATH') or exit('No direct script access allowed');

class MY_Router extends CI_Router
{
    protected function _set_request($segments = [])
    {
        parent::_set_request($segments);
        $this->_set_params($segments);
    }
    protected function _set_params($params = [])
    {
        foreach($params as $key => $value) {
            if( FALSE !== strpos($value, ':') && preg_match('/^([a-z0-9\-_]+)\:(.*)$/iu',$value,$m) ) {
                $this->uri->params[$m[1]] = $m[2];
                unset($params[$key]);
                continue;
            }
        }
    }
}

其次,在“application/core”文件夹中创建另一个文件“MY_URI.php”:

<?php defined('BASEPATH') or exit('No direct script access allowed');

class MY_URI extends CI_URI
{
    public $params = [];
    
    public function param($n, $no_result = NULL)
    {
        return isset($this->params[$n]) ? $this->params[$n] : $no_result;
    }
}
function param($n, $no_result = NULL)
{
    return get_instance()->uri->param($n, $no_result);
}

就是这样,现在您可以考虑以下示例来获取单独的 url 参数:

$param1 = $this->uri->param('param1') // output = value1
$param2 = $this->uri->param('param2') // output = value2
$param3 = $this->uri->param('param3') // output = null
$param4 = $this->uri->param('param4', 1) // output = 1

$param1 = param('param1') // output = value1
$param2 = param('param2') // output = value2
$param3 = param('param3') // output = null
$param4 = param('param4', 1) // output = 1

另外,我已经写了一个小库来处理在 url 中使用冒号,你可以从这个 github 存储库中找到它:Codeigniter Colon URI

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    相关资源
    最近更新 更多