php中的正则表达式,编译失败


Regular Expression in php, compilation failed

$string = '/product/list.html?a=b';
$regex = '#^^/(?P['w]+)/(?P['w]+)(?P[^'.]*)'.*(?P[html|xml|json]*)(?P['?.*]*)$$#';
$count = preg_match($regex, $string, $matches);

当我运行上面的代码时,它会抛出这样的警告:

Warning: preg_match(): Compilation failed: unrecognized character after (?P at offset 6 in php shell code on line 1

我看不出问题在哪里?

(?P用于启动命名为的捕获组。语法为:

(?P<name>regexp)

当您使用此语法时,将在$matches['name']中找到与regexp匹配的字符串部分。

您的regexp中缺少<name>

新方案;)

工作方式://someurl/index.php/controller/action

    if (array_key_exists('PATH_INFO', $_SERVER)) {
        $parts = explode('/', trim($_SERVER['PATH_INFO'], ' /'));
        @list($controller, $action) = $parts;
        $params = array_slice($parts, 2);
        $controller = empty($controller) ? 'default' : ucfirst(strtolower($controller));
        $action = empty($action) ? 'default' : strtolower($action);
    } else {
        $params = array();
        $controller = 'default';
        $action = 'default';
    }

这样不是更简单吗?(将'default'更改为您想要的任何内容)

你的正则表达式似乎有点错,也许你试图得到这个:

#^/(?P<folder>['w]+)/(?P<name>['w]+)'.(?P<ext>html|xml|json)'?(?P<query>.*)$#

例子结果:

0 -> /product/list.html?a=b
folder -> product
name -> list
ext -> html
query -> a=b