I would like to detect with php
if a string like $string
include duplicate trailing slashes.
For example:
$string = "http://somepage.com/something/some.html/////";
to
$string = "http://somepage.com/something/some.html";
And I wanna do an if
, if it has duplicate, something like:
If ($string = "http://somepage.com/something/some.html/////";) {
remove extra trailing slashes
}
//else do nothing...
apply
rtrim
like soThere 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 thehttp://
, 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
Live test: http://ideone.com/1qHR9o
Explanation
From your question I understand that you always get a complete URL, so, we can split it in two parts:
Now we remove the duplicated
/
with:Then we remove the extra
/
from the end of the string:And implode it back:
rtrim
is the best solution but since you taggedregex
for completeness:You can just use
rtrim()
:If you for some reason want to first check if it has trailing slashes then you can check the last character, like so:
Throwing the string through
rtrim()
is not expensive so you do not really have to check for trailing slashes first.Using regular expressions to trim trailing slashes is a little over-kill.