我想重定向/spam/(.*)
到/$1
(包括/spam/
到/
)和/spam
到/
,但不是/spam(.*)
到$1
或/$1
。
所以/spam/eggs/bacon
变成了/eggs/bacon
,/spam/
都/spam
变成了/
,spameggs/bacon
又不变成了eggs/bacon
。
什么正则表达式配对来完成这个(chars)
?$1
很简单:^.*((?<=^/spam/).*|(?<=^/spam))$
到/$1
'/spam' --> '/'
'/spam/' --> '/'
'/spam/one' --> '/one'
'/spam/one/two' --> '/one/two'
我不确定 RegExp 的风格,但我会尝试类似...</p>
/(spam($|/))?(.*)
==>/$3
这是一个 PHP 示例。
$rx = '~/(spam($|/))?(.*)~';
$arr = array(
'/spam',
'/spam/',
'/spam/eggs/bacon',
'spameggs/bacon',
'/spameggs/bacon'
);
foreach ($arr as $val) {
echo "<b>Before:</b> $val\n<b>After:</b> " . preg_replace($rx,'/$3',$val) . PHP_EOL.PHP_EOL;
}
输出
之前: /垃圾邮件
之后: /之前: /垃圾邮件/
之后: /之前: /spam/eggs/bacon
之后: /eggs/bacon之前: spameggs/培根
之后: spameggs/培根之前: /spameggs/bacon
之后: /spameggs/bacon
图案:/spam(?:/(.*)|()$)
代替:/$1
这将正确替换,是迄今为止发布的最简单的解决方案,并且如果路径不是您正在考虑的形式(即如果它不匹配/spam
或/spam/___)