0

我想重定向/spam/(.*)/$1(包括/spam//)和/spam/,但不是/spam(.*)$1/$1

所以/spam/eggs/bacon变成了/eggs/bacon/spam//spam变成了/spameggs/bacon又不变成了eggs/bacon

什么正则表达式配对来完成这个(chars)$1

4

3 回答 3

1

很简单:^.*((?<=^/spam/).*|(?<=^/spam))$/$1

测试http://ideone.com/YqAAA):

'/spam'          --> '/'
'/spam/'         --> '/'
'/spam/one'      --> '/one'
'/spam/one/two'  --> '/one/two'
于 2012-08-21T00:51:23.783 回答
1

我不确定 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

于 2012-08-21T00:55:05.850 回答
0

图案:/spam(?:/(.*)|()$)

代替:/$1

这将正确替换,是迄今为止发布的最简单的解决方案,并且如果路径不是您正在考虑的形式(即如果它不匹配/spam/spam/___)

于 2012-08-21T00:53:39.283 回答