Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find last character in a string in PHP

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 "/"?

like image 674
Bob Cavezza Avatar asked Dec 13 '10 08:12

Bob Cavezza


People also ask

How do you check what the last character of a string is?

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.

How can I match a character in a string in PHP?

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.

How can I get the last word in PHP?

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.

How do I get the first character of a string in PHP?

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.


1 Answers

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, '/').'/';
like image 54
powtac Avatar answered Oct 21 '22 16:10

powtac