There are places where / can be duplicated, for example, you can access your question through all these links:
The only double / that matters here is http:// , so consider it. rtrim will not work on rtrim own in most cases that I have provided, so release regular expressions.
Decision
$parts = explode('//', $full_url, 2); $parts[1] = rtrim(preg_replace('@/ +@ ', '/', $parts[1]), '/'); $full_url = implode('//', $parts); unset($parts);
Live test: http://ideone.com/1qHR9o
Before: /questions/1460693/remove-duplicate-trailing-slashes After: https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes --------------------- Before: /questions/1460693/remove-duplicate-trailing-slashes/// After: https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes --------------------- Before: https://stackoverflow.com///questions///13990256///remove-duplicate-trailing-slashes//// After: https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes --------------------- Before: https://stackoverflow.com/questions//13990256/remove-duplicate-trailing-slashes// After: https://stackoverflow.com/questions/13990256/remove-duplicate-trailing-slashes ---------------------
Description
From your question, I understand that you always get the full URL, so we can split it into two parts:
$parts = explode('//', $full_url, 2);
Now we will remove the duplicated / using:
preg_replace('@/ +@ ', '/', $parts[1])
Then we remove the extra / from the end of the line:
$parts[1] = rtrim( , '/');
And bring it back:
$full_url = implode('//', $parts); unset($parts);