In this tutorial, You will learn how to remove last character from string in PHP.
How to Remove the Last Character from a PHP String
There are different ways to remove the last character from a string, depending on the specific use case and the nature of the string:
Method 1: Using substr method
You can use the substr
method of PHP to remove the last character from the string.
The syntax of subster method is given below:
substr($string, 0, -1);
Here is code using substr:
$string = "Hello World!"; echo "Given string: " . $string . "\n"; echo "Updated string: " . substr($string, 0, -1) . "\n";
Output
Given string: Hello World! Updated string: Hello World
Method 2: Using substr_replace method
You can also use substr_replace
to remove the last character from the string in PHP.
The basic syntax of substr_replace
function is:
substr_replace($string ,"", -1);
Here is an example code:
$string = "Hello World!"; echo "Given string: " . $string . "\n"; echo "Updated string: " . substr_replace($string ,"",-1) . "\n";
Output
Given string: Hello World!
Updated string: Hello World
Recommended Posts:
To remove specific and special characters from string PHPMethod 3: Using rtrim() Method
The rtrim() method also used to remove the last character from the given string in PHP.
The basic syntax of rtrim() function is:
rtrim($string,'a');
Here “a” is the character that you want to remove in your string.
Here is an example source code:
$string = "Hello World!"; echo "Given string: " . $string . "\n"; echo "Updated string: " . rtrim($string, "!") . "\n";
Output
Given string: Hello World! Updated string: Hello World
PHP remove the last character from the string if comma?
If you have a comma separate string in PHP and want to remove the last character from the string if comma, you can use PHP rtrim()
method like the following:
$string = "remove comma from end of string php,"; echo "Given string: " . $string . "\n"; echo "Updated string: " . rtrim($string, ",") . "\n";
Output
Given string: remove comma from end of string php, Updated string: remove comma from end of string php
Conclusion
In conclusion, you have learned 4 methods to remove last characters from string in php.
Helpful for substr_replace, substr or trim function to remove the last character from a string in PHP.
Thanks tutsmake.com for remove last character from string in php.
How to remove last 3 character from string php?
Using substr() function, You can remove 3 characters at the end of a string in PHP.
like this :-
echo substr($string, 0, -3);