How to Remove the Last Character from a String in PHP

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.

Watch a course Learn object oriented PHP

The First Option is Substr Function

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

<?php

substr($string, 0, -1);

?>

A simple example of the substr function is illustrated below:

<?php

$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

The Second Option is Substr_replace Function

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

<?php

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

?>

And here is an example of using the substr_replace function:

<?php

$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

The Third Option is Rtrim() Function

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

Here is the basic syntax:

<?php

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:

<?php

$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.