首页 > php框架 > CI框架中PHP正则(不用转义)做法

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

PHP正则表达式在碰到要与正则相同的字符串时我们需要转义了,下面小编修改了CI框架中PHP正则之后我们再使用时不需要转义了可以直接使用,具体如下。

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

为了避免这个情况,可以把正则的修饰定义符定义为 # 。

例子:

<?php
$uri = 'art/33/44';
preg_match_all('#^art(/\d+)(/\d+)#', $uri, $arr);
//等价于下面注释的
//preg_match_all('/^art(\/\d+)(\/\d+)/',$uri,$arr);
echo '<pre>';
var_dump($arr);

话说CI框架,在路由解析功能上。也是这么干的。CI相关代码如下:

[路由定义文件application/config/routesphp]

$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 '<br>';
        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框架里书写路由规则的时候,如果正则规则里有 / , 则可以不用转义!


本文地址:http://www.phprm.com/frame/72695.html

转载随意,但请附上文章地址:-)

标签:foreach explode preg_match request

相关文章

发表留言