Remove the last character from a string in PHP

In this tutorial, you will learn how to remove the last character from a string in php. Here we explain to you three methods to do this task.

Remove the last character from a string in PHP, Delete the last character of a string, rtrim function, substr_replace function, substr function, Remove last comma from the string. get last character of string php, remove unwanted characters from string php, remove last character from string javascript.

Different way to remove the last character from a string

  1. rtrim function
  2. substr function
  3. substr_replace function

Method 1: rtrim function

Using the rtrim function, we can remove the last specific characters from the string. By default this function removes whitespace from the end of string.

Syntax: Example:

In some cases, the rtrim function will not work for us because it removes all specific characters from the end of string. Let’s be clear with an example.

Here, if we want to remove only single . character from the end of the string but rtrim function removes all . characters. In this case we can use the substr function or substr_replace function of php.

Method 2: substr function

We can use the substr function to remove last characters from the string.

Syntax: Example:

Another example where you can see its remove only one character if more than one same characters are available at the end of string and want to remove only one of them last character.

Method 3: substr_replace function

Also, you can use the substr_replace function to remove the last character from a string.

Syntax: Example:

That’s it for today.
Thank you for the reading. Happy Coding!

You may also like...

Leave a Reply

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