Remove Last Character from String in PHP

Remove last character from a string in php; In this tutorial, You will learn how to remove last character from a string with example code. PHP has functions for removing the last character from the given string. Let’s see the examples of php funcations to remove last character from given string.

Method 1: using substr function

You can use the substr() function to remove the last character from any string in PHP.

Syntax:

substr($string, 0, -1);

Example:

<?php
$string = "Hello world!";
echo "Original string: " . $string . "\n";
 
echo "Updated string: " . substr($string, 0, -1) . "\n";
?>

Output:

Original string: Hello World!
Updated string: Hello TecAdmin

Method 2: Using substr_replace function

You can also use the PHP substr_replace() function to remove the last character from a string in PHP.

Syntax:

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

Example:

<?Php
$string = "Hello World!";
echo "Original string: " . $string . "\n";
 
echo "Updated string: " . substr_replace($string ,"",-1) . "\n";
?>

Output:

Original string: Hello World!
Updated string: Hello World

Method 3:Using mb_substr function

You can use the mb_substr function to remove characters from the end of the string.

Syntax:

mb_substr($string, 0, -1);

Example:

<?php
$string = "Hello World!";
echo "Original string: " . $string . "\n";
 
echo "Updated string: " . mb_substr($string, 0, -1) . "\n";
?>

Output:

Original string: Hello World!
Updated string: Hello World

Method 4: Using rtrim function

The rtrim function to used to remove specific characters from the end of the string.

Syntax:

rtrim($string,'o');

Here “0” is the character to remove.

Example:

<?php
$string = "Hello World!";
echo "Original string: " . $string . "\n";
 
echo "Updated string: " . rtrim($string, "!") . "\n";
?>

Output:

Original string: Hello World!
Updated string: Hello World