Remove Last Character from String in PHP
In this blog post, we will help our users to learn about how they can remove the last character from a string in PHP. A string is a sequence of characters mentioned in double quotes while writing the program.
Remove the last character from string in PHP
There are 4 main methods available in PHP to complete the above problem. These methods are listed below:
- Use of substr_replace()
- Use of substr function
- Use of mb_substr function
- Use of rtrim function
Let’s check these functions one by one. Firstly we will see the substr_replace function. The following example demonstrates the same:
<?Php // Defining String $string = "Hello StudyExperts!"; echo "Original string: " . $string . "\n"; // calling substr function on the original string echo "Updated string: " . substr_replace($string ,"",-1) . "\n"; ?>
Output
As one can see the last character is the exclamation mark which is not there in the updated string as we are replacing it with the blank space. Now let’s move on to the substr function. The example for the same is also shown below:
<?php $string = "Hello StudyExperts!"; echo "Original string: " . $string . "\n"; echo "Updated string: " . substr($string, 0, -1) . "\n"; ?>
Output
In the case of mb_suubstr, it removes characters from the last of the strings. The code for the same is also shown below:
<?php $string = "Hello StudyExperts!"; echo "Original string: " . $string . "\n"; echo "Updated string: " . mb_substr($string, 0, -1) . "\n"; ?>
Output
The last one is the rtrim function that trims the specific numbers of characters from the end of the string. The code for the same is:
<?php $string = "Hello StudyExperts!"; echo "Original string: " . $string . "\n"; echo "Updated string: " . rtrim($string, "!") . "\n"; ?>
Output
Also Read: AlphaGo: Program that plays the board game Go