There are places where /
can be duplicated, for example, you can access your question through all these links:
The only double /
that makes difference here is the http://
, so let's consider it. rtrim
alone will not work in most of the cases I provided, so let's go with regular expressions.
Solution
$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: 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
---------------------
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
---------------------
Explanation
From your question I understand that you always get a complete URL, so, we can split it in two parts:
$parts = explode('//', $full_url, 2);
Now we remove the duplicated /
with:
preg_replace('@/+@', '/', $parts[1])
Then we remove the extra /
from the end of the string:
$parts[1] = rtrim( /*previous line*/ , '/');
And implode it back:
$full_url = implode('//', $parts);
unset($parts);