Appearance
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.
Option 1: substr
The substr function extracts a substring. To remove the last character, specify a negative length:
php substr function syntax
php
<?php
substr($string, 0, -1);
?>A simple example of the substr function is illustrated below:
php substr function
php
<?php
$string = "Hello World!";
echo "Given string: " . $string . "\n";
echo "Updated string: " . substr($string, 0, -1) . "\n";
?>The output will look as follows:
php substr function output
text
Given string: Hello World!
Updated string: Hello WorldNote: For multibyte strings (e.g., UTF-8), use
mb_substr($string, 0, -1, 'UTF-8')to avoid cutting characters in half. Also, if the string is empty or contains only one character, the function will return an empty string.
Option 2: substr_replace
The substr_replace function replaces part of a string. To remove the last character, replace it with an empty string:
php substr replace syntax
php
<?php
substr_replace($string, "", -1);
?>And here is an example of using the substr_replace function:
php substr replace
php
<?php
$string = "Hello World!";
echo "Given string: " . $string . "\n";
echo "Updated string: " . substr_replace($string, "", -1) . "\n";
?>And, here is the output:
php substr replace output
text
Given string: Hello World!
Updated string: Hello WorldOption 3: rtrim
The rtrim function removes trailing whitespace or specified characters from the end of a string. It removes all trailing occurrences of the characters in the mask, not just the last character. To remove a specific trailing character, pass it as the second argument:
php rtrim
php
<?php
rtrim($string, "!");
?>So, an example of removing the character will look as follows:
php remove string character
php
<?php
$string = "Hello World!";
echo "Given string: " . $string . "\n";
echo "Updated string: " . rtrim($string, "!") . "\n";
?>And, the output is the following:
php remove character from string output
text
Given string: Hello World!
Updated string: Hello WorldSo, 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.