How to Remove Last Character from String in PHP

Channel: Linux
Abstract: php $string = "Hello TecAdminphp $string = "Hello TecAdmin

Question – How do I remove last character from a string in PHP script? In this tutorial you will learned multiple methods to remove last character from a string using php.

This tutorial describes 4 methods to remove last character from a string in PHP programming language. You can use any one of the following methods as per the requirements.

  • Don’t Miss – Check If String Contains a Sub String in PHP
Method 1 – Using substr_replace function

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

Syntax:

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

Example:

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

Output:

Original string: Hello TecAdmin!
Updated string: Hello TecAdmin
Method 2 – substr function

Use the substr function to remove the last character from any string in PHP string

Syntax:

substr($string, 0, -1);1substr($string, 0, -1);

Example:

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

Output:

Original string: Hello TecAdmin!
Updated string: Hello TecAdmin
Method 3 – mb_substr function

Use the mb_substr function to remove characters from the end of the string.

Syntax:

mb_substr($string, 0, -1);1mb_substr($string, 0, -1);

Example:

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

Output:

Original string: Hello TecAdmin!
Updated string: Hello TecAdmin
Method 4 – rtrim function

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

Syntax:

rtrim($string,'x');1rtrim($string,'x');

Here 「x」 is the character to remove.

Example:

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

Output:

Original string: Hello TecAdmin!
Updated string: Hello TecAdmin

Ref From: tecadmin

Related articles