In this exercise, you will learn how to remove the last character from a string using PHP.
This is a very common PHP interview question and generally asked in programming interviews, 'how to remove the last character from string in PHP'. Or, during the development process, you may come across a situation where you need to eliminate the last character from a string. This exercise shows you different ways to achieve the process from the given string. You can use any of the following methods to remove the last character from the string.
Method1: using substr() function
This function is used to return a part of a string or substring from a string, starting from a given position.
Syntax -
substr(string,start,length)The string is the required parameter. It should be a string datatype, start specifies where to start in the string and length is an optional parameter. If it is positive, the returned string contains the length characters from the beginning, and if it is negative, the returned string contains the length characters from the end of the string.
Example -
<?php $str1 = "Good Morning!"; echo "Original string: " . $str1 . "<br/>"; echo "Updated string: " . substr($str1, 0, -1) . "<br/>"; ?>Output -
Original string: Good Morning! Updated string: Good MorningMethod 2: using mb_substr() function
It returns the part of the string. It performs a multi-byte safe substr() operation based on the number of characters. The position is counted from the beginning of the string.
Syntax -
mb_substr ( string $str , int $start [, int $length = NULL [, string $encoding = mb_internal_encoding() ]] )Here, the $str is the string to extract the substring from, $start specifies where to start in the string, $length specifies the maximum number of characters to use from $str.
Example -
<?php $str1 = "Good Morning!"; echo "Original string: " . $str1 . "<br/>"; echo "Updated string: " . mb_substr($str1, 0, -1) . "<br/>"; ?>Output -
need an explanation for this answer? contact us directly to get an explanation for this answerOriginal string: Good Morning! Updated string: Good Morning