PHP: Remove the last character from a string.

This is a guide on how to remove the last character from a string in PHP. To do this, we can use either the rtrim function or the substr / mb_substr function.

Using the rtrim function to remove the last character.

By default, PHP’s rtrim function will strip whitespace from the end of a string. However, you can also tell it to remove other characters.

Take a look at the following example:

In the code snippet above, we used rtrim to remove the full stop from the end of our string.

You can also provide PHP’s rtrim function with multiple characters:

If you use the character mask above, you will see that the string “Hello.” becomes “Hell”

In certain cases, the rtrim function will not work. For example, what if we only wanted to remove the last comma in the string below?

The problem here is that rtrim will remove all instances of the character from the end of the string. i.e. It removed both commas when we only wanted it to remove one.

In cases like this, we will need to use PHP’s substr function instead.

Using PHP’s substr function to remove the last character.

PHP’s substr function is designed to return a part / subset of a given string. However, it can also be used to remove the last character of a string.

Take the following example:

In the PHP above, we provided the substr function with three parameters:

  1. The string that we want to remove our character from.
  2. The $start parameter, which we set to 0 because we want the entire left side of the string.
  3. The $length parameter, which we set to -1. By setting the $length parameter to -1, we are basically telling PHP that we want our sub-string to end before the last character. This leaves us with everything except the final character.

Removing special characters from the end of a PHP string.

In some cases, you might be dealing with special characters from other languages. In those cases, the regular substr function will not work.

An example:

Here, we attempted to remove the German umlaut character from the end of a string. However, this left us with a garbled string that contains replacement characters.

To remove special characters, you will need to use the mb_substr function instead:

If you change substr to mb_substr, you will see that the special character has been successfully removed. This is because the mb_substr function performs a multi-byte safe operation.

Related: Get the last character of a string using PHP.

Facebook Comments