一聚教程网:一个值得你收藏的教程网站

热门教程

CI框架中PHP正则(不用转义)做法

时间:2022-06-25 00:53:39 编辑:袖梨 来源:一聚教程网

我们在书写PHP正则的时候,正则的修饰定义符通常定义为 / ,而定义为 / 的带来的麻烦是如果正则表达式含中有 / 则需要转义书写为 \/ 这让读正则的人看的比较晕乎。书写也比较烦琐。
为了避免这个情况,可以把正则的修饰定义符定义为 # 。

例子:

 代码如下 复制代码
$uri = 'art/33/44';
preg_match_all('#^art(/\d+)(/\d+)#',$uri,$arr);
//等价于下面注释的
//preg_match_all('/^art(\/\d+)(\/\d+)/',$uri,$arr);
echo '
';
var_dump($arr);

话说CI框架,在路由解析功能上。也是这么干的。CI相关代码如下:
[路由定义文件 application/config/routes.php]

 代码如下 复制代码
$route['default_controller'] = "welcome";
$route['404_override'] = '';
$route['art/(\d+)(/\d*)'] = "test/aaa/$1/";

[路由解析类 system/core/Router.php]

 代码如下 复制代码

function _parse_routes()
{
// Turn the segment array into a URI string
$uri = implode('/', $this->uri->segments);
// Is there a literal match?  If so we're done
if (isset($this->routes[$uri]))
{
return $this->_set_request(explode('/', $this->routes[$uri]));
}

// Loop through the route array looking for wild-cards
foreach ($this->routes as $key => $val)
{
// Convert wild-cards to RegEx
$key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key));

// Does the RegEx match?
echo '#^'.$key.'$#'.'---'.$uri;
echo '
';
if (preg_match('#^'.$key.'$#', $uri))
{
// Do we have a back-reference?
if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE)
{
$val = preg_replace('#^'.$key.'$#', $val, $uri);
}

return $this->_set_request(explode('/', $val));
}
}

// If we got this far it means we didn't encounter a
// matching route so we'll set the site default route
$this->_set_request($this->uri->segments);
}

这样的话,在CI框架里书写路由规则的时候,如果正则规则里有/,则可以不用转义!

热门栏目