这是一种将正则表达式与explode() 相结合的解决方案,因为我很确定不可能使用 PCRE 单独捕获(或计数)重复组。
正则表达式模式期望/propertyComplexity 之后的任何/ 分隔段(我已经在斜线前面加了一点更严格)是非空的,因此允许任何非空内容,而不仅仅是被包围的内容通过大括号,如{type}。
该模式比它可能需要的要复杂一些,但它使分解结果更简短(无需修剪斜线)。
实际的参数值将在数组$arguments 中,但我没有在结果中显示这些值以更简短一些。
$urls = array(
'/json/score/propertyComplexity',
'/json/score/propertyComplexity/',
'/json/score/propertyComplexity//', // invalid
'/json/score/propertyComplexity/{type}',
'/json/score/propertyComplexity/{type}/',
'/json/score/propertyComplexity/{type}//', // invalid
'/json/score/propertyComplexity/{type}/{code}',
'/json/score/propertyComplexity/{type}/{code}/{param3}',
'/json/score/propertyComplexity/{type}/{code}/{param3}/{param4}',
'/json/score/propertyComplexity/{type}/{code}/{param3}/{param4}/{param5}'
);
foreach( $urls as $url ) {
printf( 'testing %s' . PHP_EOL, $url );
if( preg_match( '~(?<=/propertyComplexity)(?:/(?<arguments>[^/]+(/[^/]+)*))?(?:/?$)~', $url, $matches ) ) {
$arguments = isset( $matches[ 'arguments' ] ) ? explode( '/', $matches[ 'arguments' ] ) : array();
printf( ' URL is valid: argument count is %d' . PHP_EOL, count( $arguments ) );
}
else {
echo ' URL is invalid' . PHP_EOL;
}
echo PHP_EOL;
}
View this example on eval.in
结果:
testing /json/score/propertyComplexity
URL is valid: argument count is 0
testing /json/score/propertyComplexity/
URL is valid: argument count is 0
testing /json/score/propertyComplexity//
URL is invalid
testing /json/score/propertyComplexity/{type}
URL is valid: argument count is 1
testing /json/score/propertyComplexity/{type}/
URL is valid: argument count is 1
testing /json/score/propertyComplexity/{type}//
URL is invalid
testing /json/score/propertyComplexity/{type}/{code}
URL is valid: argument count is 2
testing /json/score/propertyComplexity/{type}/{code}/{param3}
URL is valid: argument count is 3
testing /json/score/propertyComplexity/{type}/{code}/{param3}/{param4}
URL is valid: argument count is 4
testing /json/score/propertyComplexity/{type}/{code}/{param3}/{param4}/{param5}
URL is valid: argument count is 5