如何使用'PREG'或'HTACCESS'从URI中删除多个斜杠

9

如何使用“PREG”或“HTACCESS”从URI中删除多个斜杠

site.com/edition/new/// -> site.com/edition/new/


site.com/edition///new/ -> site.com/edition/new/

谢谢

5个回答

30
$url = 'http://www.abc.com/def/git//ss';
$url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
// output http://www.abc.com/def/git/ss

$url = 'https://www.abc.com/def/git//ss';
$url = preg_replace('/([^:])(\/{2,})/', '$1/', $url);
// output https://www.abc.com/def/git/ss

很好的答案,您能否解释一下这个正则表达式是如何工作的? - Gihan
在由@ツLiverbool链接的工具中,将([^:])(\/{2,})作为正则表达式粘贴,然后将$url作为测试字符串或任何其他要测试的URL粘贴。 - briankip
@Gilhan 序列[...]表示匹配其中任何一个字符。在这种情况下,[^:]表示匹配除冒号以外的任何字符。前导^否定了该序列。 此序列被括号括起来,使其成为“捕获组”,捕获的值可以在替换中使用为$1。 序列[/]{2,}表示查找两个或更多的正斜杠。 因为整个表达式由正斜杠分隔,所以要匹配的正斜杠必须进行转义,这就是反斜杠的作用。 此序列也被括号括起来,因此也被捕获,但不是必需的。 - bseddon
注意,答案中提供的示例无法处理存在多个正斜杠序列的情况,例如:https://www.example.com/def//git//ss因为该表达式只会匹配第一个实例。为解决这个问题,应该使用“贪婪”指令:preg_replace('/([^:])/{2,}/g', '/') - bseddon

16

在正则表达式中使用加号符号+表示前一个字符的出现一次或多次。因此,我们可以将它添加到preg_replace中,通过一个替换将一个或多个/ 的出现替换为一个

   $url =  "site.com/edition/new///";

$newUrl = preg_replace('/(\/+)/','/',$url);

// now it should be replace with the correct single forward slash
echo $newUrl

好主意,但是在“edition”之后如何进行检查呢? 就像这个例子一样:$ url =“site.com/edition///new///”; $ newUrl = preg_replace('/ edition(\ / +)/','/',$ url);我不知道该怎么应用。 - Lelis
注意方案中的双斜杠!!!这将替换方案中的双斜杠,因此任何URL http:// 将变成只有一个斜杠的 http:/ - Aram Hovhannisyan

1
简单,看这个例子:
$url ="http://portal.lojav1.local//Settings////messages";
echo str_replace(':/','://', trim(preg_replace('/\/+/', '/', $url), '/'));

输出:
http://portal.lojav1.local/Settings/messages

0

http://domain.com/test/test/ > http://domain.com/test/test

的意思是:

# Strip trailing slash(es) from uri
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+?)[/]+$ $1 [NC,R,L]

http://domain.com//test//test// > http://domain.com/test/test/

的翻译是:

{{链接1:http://domain.com//test//test//}} > {{链接2:http://domain.com/test/test/}}

# Merge multiple slashes in uri
RewriteCond %{THE_REQUEST} ^[A-Z]+\ //*(.+)//+(.*)\ HTTP
RewriteRule ^ /%1/%2 [R,L]
RewriteCond %{THE_REQUEST} ^[A-Z]+\ //+(.*)\ HTTP
RewriteRule ^ /%1 [R,L]

如果测试后一切正常,请将R更改为R=301...

有人知道如何在使用上述方法时保留查询中的双斜杠吗?

(例如:/test//test//?test=test//test > /test/test/?test=test//test)


我试过了,但是它不起作用! - Sharad Upadhyay

0

编辑:哈哈,我把这个问题看成“不用preg”了,算了:3

function removeabunchofslashes($url){
  $explode = explode('://',$url);
  while(strpos($explode[1],'//'))
    $explode[1] = str_replace('//','/',$explode[1]);
  return implode('://',$explode);
}

echo removeabunchofslashes('http://www.site.com/edition////new///');

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接