how to remove multiple slashes in URI with \'PREG\' or \'HTACCESS\'
site.com/edition/new/// -> site.com/edition/new/
site.com/edition///new/ -> site.co
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///');
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
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)
$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
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