I'm doing some url rewriting in PHP and need to find URLS with a slash at the end and then do a 301 redirect. I thought there'd be a simple PHP function to find last string, but I couldn't find anything. First instincts make m think I need to use regex, but I'm not 100%.
Here's one example:
http://domainx.com/characters/ I want to find a trailing slash and turn it into http://domainx.com/characters
So what function will help me check if the last character is a "/"?
You can use
substr
: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.You can use basename()
This will return
characters
forhttp://domainx.com/characters/
as well ashttp://domainx.com/characters
You can do like this:-
Then you can use the
$module
directly in your conditional logic without doing any redirects.If you want to collect the last
/
trimmed URL then you can do this:-If you are storing the project base url in a config file:-
then you can do this:-
A nice solution to remove safely the last
/
is to usertrim()
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:If you have php > 7.1
Will give you the last character
http://sandbox.onlinephpfunctions.com/code/ff439889f14906749e4eb6328796c354c60f269b
$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.You could
preg_replace()
a/
at the end of the subject