如果组存在,我如何捕获它,但如果不存在,则匹配正则表达式的其余部分


How can I capture a group if it exists but if not, match the rest of the regex?

我有以下pcre regex:

^(.+'/.*'.php)('?)?('/.+)$

这个例子URL:

/subdir/file.php/this/is/a/path/info?par=am1&param=2

前面写的正则表达式捕获#1组/subdir/file.php和#2组/this/is/a/path/info?par=am1&param=2。

我需要将参数分成第四组(在?之后)。并得到以下内容:

组#1:/subdir/file.php组3:/this/is/a/path/info第4组:?par=am1&param=2

有时候,URL没有参数。在本例中,我只需要匹配#1和#2组。

我试过了:

^(.+'/.*'.php)('?)?('/.+)('?.*)$

但是如果URL没有参数,它将不匹配#1和#3组(/subdir/file.php和/this/is/a/path/info)

我该怎么做?

谢谢!

您可以使用 urlparse preg_split 来分割获得的路径:

$url = "/subdir/file.php/this/is/a/path/info?par=am1&param=2";
$pth = parse_url($url, PHP_URL_PATH);
$chunks = preg_split('~(?<='.php)(?=/)~', $pth);
foreach ($chunks as $chunk) {
    echo $chunk . "'n"; // =>  /subdir/file.php and  /this/is/a/path/info
}
echo parse_url($url, PHP_URL_QUERY) . "'n"; // => par=am1&param=2

查看PHP演示

请注意,使用preg_split('~(?<='.php)(?=/)~', $pth),您将在最后获得与some.php相同数量的块,因为路径中有这样的块。(?<='.php)(?=/)模式匹配.php/子字符串之间的空位置。

相关文章: