9

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

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


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

谢谢

4

5 回答 5

28
$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
于 2013-08-01T16:03:32.993 回答
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
于 2011-06-14T05:07:29.493 回答
1

简单,检查这个例子:

$url ="http://portal.lojav1.local//Settings////messages";
echo str_replace(':/','://', trim(preg_replace('/\/+/', '/', $url), '/'));

输出 :

http://portal.lojav1.local/Settings/messages
于 2016-07-12T17:58:20.410 回答
0

编辑:哈,我把这个问题读成“没有怀孕”哦: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///');
于 2011-06-14T05:06:03.630 回答
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/

# 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)

于 2012-03-07T13:22:05.833 回答