Find last character in a string in PHP
A nice solution to remove safely the last /
is to use
$string = rtrim($string, '/');
rtrim()
removes all /
s on the right side of the string when there is one or more.
You can also safely add exactly one single /
at the end of an URL:
$string = rtrim($string, '/').'/';
You can use substr
:
substr($str, -1)
This returns the last byte/character in a single-byte string. See also the multi-byte string variant mb_substr
.
But if you just want to remove any trailing slashes, rtrim
is probably the best solution.
And since you’re working with URLs, you might also take a look at parse_url
to parse URLs as a trailing slash does not need to be part of the URL path.
$string[strlen($string)-1]
gives you the last character.
But if you want to strip trailing slashes, you can do $string = rtrim($string, '/');
. If there is no trailing slash, $string
will remain unchanged.