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 "/"?
To get the last character of a string, use bracket notation to access the string at the last index, e.g. str[str. length - 1] . Indexes are zero-based, so the index of the last character in the string is str.
The strrchr() function finds the position of the last occurrence of a string within another string, and returns all characters from this position to the end of the string.
strrpos() Function: This inbuilt function in PHP is used to find the last position of string in original or in another string. It returns the integer value corresponding to position of last occurrence of the string, also it treats uppercase and lowercase characters uniquely.
To get the first character from a string, we can use the substr() function by passing 0,1 as second and third arguments 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, '/').'/';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With