有些地方/
可以重复,例如,您可以通过所有这些链接访问您的问题:
唯一不同的双倍/
是http://
,所以让我们考虑一下。rtrim
在我提供的大多数情况下,单独使用是行不通的,所以让我们使用正则表达式。
解决方案
$parts = explode('//', $full_url, 2);
$parts[1] = rtrim(preg_replace('@/+@', '/', $parts[1]), '/');
$full_url = implode('//', $parts);
unset($parts);
现场测试: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
---------------------
解释
根据您的问题,我了解到您始终会获得完整的 URL,因此,我们可以将其分为两部分:
$parts = explode('//', $full_url, 2);
现在我们删除重复/
的:
preg_replace('@/+@', '/', $parts[1])
/
然后我们从字符串末尾删除多余的部分:
$parts[1] = rtrim( /*previous line*/ , '/');
并将其内爆:
$full_url = implode('//', $parts);
unset($parts);