Remove the Last Character from a String in PHP

To remove the last character from a string in PHP, we can use these functions: rtrim, substr, and mb_substr.

Table of Contents

rtrim

The rtrim() function removes whitespace or other predefined characters from the right side of a string. By default, it removes white spaces. We can modify ít parameters to make it remove any defined characters at the last positions.

$str = "Hello developers!!!";
$str = rtrim($str, "!");
echo $str; //=> Hello developers
$str = rtrim($str, "s!"); 
echo $str; //=> Hello developer

As you see in the example with rtrim($str, "!"), it removes all instances of “!” which appear at the end. So it is not ideal if you only want to remove only the last character.

substr

This function returns the portion of the string specified by the start and length parameters.

substr ( string $string , int $start [, int $length ] ) : string

If $lenght is negative, the result will start at the start’th character from the end of the string. To take out the last character, we will use a negative value for $length.

$source = "tldevtech website!";
$source = substr($source, 0, -1);
echo $source; //=> tldevtech website
$source = substr($source, 0, -2);
echo $source; //=> tldevtech websit

mb_substr

If the source string contains special characters such as Chinese characters, substr doesn’t work. The returned string will show the last character as a broken symbol as below.

$source = "tldevtech does not contain 打印";
$source = substr($source, 0, -2);
echo $source; //=> tldevtech does not contain 打�

In this case, we must use mb_substr which performs a multi-byte safe substr() operation based on a number of characters.

$source = "tldevtech does not contain 打印";
$source = mb_substr($source, 0, -2);
echo $source; //=> tldevtech does not contain 
$source = "other special character is ôê";
$source = mb_substr($source, 0, -3);
echo $source; //=> other special character is

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close