Home > Article > Backend Development > How to delete the last character after output in php
php method to delete the last character after output: 1. Use the substr and strlen functions to delete the last character; 2. Directly use the substr function to trim the last character in reverse order; 3. Use rtrim to delete the string Terminal whitespace characters.
The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer
How to delete the last character after output in php ?
Summary of the three methods of deleting the last character of a string in PHP
1. Preface
Read from the database with select() When providing one-to-many information, it is often necessary to split the retrieved array with a specific character and then concatenate it into a string.
Common syntax format:
foreach ($arr as $key => $value) {2 $arr_str = $arr['x_id'] . ',' . $arr_str;3 }
Assume that the characters in the character array $arr are
arr[0] = 'a';2 arr[1] = 'b';3 arr[2] = 'c';
, then the spliced $arr_str string is a, b, c , at this time, we need to delete the last character ','.
2. Summary of the method of deleting the last character in PHP:
Method 1:
substr($arr_str,0,strlen($arr_str)-1);
Detailed explanation: substr() function syntax: string substr (string $string, int $start [, int $length ] )
strlen() function syntax: int strlen ( string $string )
Principle of this example:
First use strlen() The function determines the length of the string $arr_str, and then uses the substr() function to intercept $arr_str to the penultimate digit of $arr_str. This removes the last ",".
Usage experience:
Not recommended, there is a simpler and more useful way in PHP!
Method 2:
substr($arr_str, 0, -1)
Detailed explanation: directly use the substr() function to cut off the last character in reverse order;
Usage experience: It is still very suitable~~However, first, You have to make sure that there must be content in the string, and the last digit must not be included!
Method 3:
rtrim($arr_str, ",")
Detailed explanation: rtrim() function syntax: string rtrim (string $str [, string $character_mask])
rtrim - delete the end of the string Blank characters (or other characters)
Usage experience:
is simply prepared for this need!
Note: After the above method operates on the string, it returns the operation result and does not change the string itself! Remember to use a variable to receive the result!
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to delete the last character after output in php. For more information, please follow other related articles on the PHP Chinese website!