How to Remove the Last Character from a String in PHP

  1. The First Option is Substr Function
  2. The Second Option is Substr_replace Functions
  3. The Third Option is Rtrim() Function

While working with PHP, it is often necessary to remove characters from strings.

In this snippet, we are going to show you several PHP functions that allow removing the last character from a particular string.

A. The First Option is Substr Function

The first option is using the substr function. The syntax of this function is the following:

substr($string, 0, -1);

A simple example of the substr function is illustrated below:

$string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . substr($string, 0, -1) . "\n";

The output will look as follows:

Given string: Hello World!
Updated string: Hello World

B. The Second Option is Substr_replace Function

The second option is using the substr_replace function. Its basic syntax is:

substr_replace($string ,"", -1);

And here is an example of using the substr_replace function:

$string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . substr_replace($string ,"",-1) . "\n";

And, here is the output:

Given string: Hello World!
Updated string: Hello World

C. The Third Option is Rtrim() Function

This function also allows removing the last character of a string.

Here is the basic syntax:

rtrim($string,'a');

In this syntax, you can notice “a” character, which should be removed.

So, an example of removing the character will look as follows:

$string = "Hello World!";
 echo "Given string: " . $string . "\n";
 echo "Updated string: " . rtrim($string, "!") . "\n";

And, the output is the following:

Given string: Hello World!
Updated string: Hello World

So, in this snippet, we discussed three ways of removing the last character from a string in PHP. These are simple actions that will help you to deal with one of the common issues in PHP.


Do you find this helpful?

Related articles