开发者

how to remove multiple slashes in URI with 'PREG' or 'HTACCESS'

how to remove multiple slashes in URI with '开发者_开发百科PREG' or 'HTACCESS'

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


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

thanks


$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


using the plus symbol + in regex means the occurrence of one or more of the previous character. So we can add it in a preg_replace to replace the occurrence of one or more / by just one of them

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

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

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


Simple, check this example :

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

output :

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


Edit: Ha I read this question as "without preg" oh well :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///');


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]

Change R to R=301 if everything works fine after testing...

Does anyone know how to preserve double slashes in query using above method?

(For example: /test//test//?test=test//test > /test/test/?test=test//test)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜