Summary: three methods for deleting the last character of a string in PHP and three methods for deleting the string
I. Preface
From databaseselect()When reading one-to-multiple information, you often need to split the retrieved array with a specific character and splice it into a string.
Common syntax formats:
foreach ($arr as $key => $value) { $arr_str = $arr['x_id'] . ',' . $arr_str; }
Assuming character array$arrThe characters in are
arr[0] = 'a'; arr[1] = 'b'; arr[2] = 'c';
Then, the spliced$arr_str The string is a, B, c. At this time, we need to delete the last character.
Ii. Summary of how to delete the last character in PHP:
Method 1:
substr($arr_str,0,strlen($arr_str)-1);
Details:substr()Function Syntax:string substr ( string $string , int $start [, int $length ] )
strlen()Function Syntax:int strlen ( string $string )
Principles of this example:
Usestrlen()Function judgment string$arr_strAnd then usesubstr()Function pair$arr_strTo$arr_str. In this way, the last "," is removed.
Experience:
Not recommended. There are more simple and easy-to-use methods in php!
Method 2:
substr($arr_str, 0, -1)
Details:Direct usesubstr()The function returns the last character in reverse order;
Usage experience: it is quite suitable ~~ However, you must first make sure that there is content in the string, and the last character must not!
Method 3:
rtrim($arr_str, ",")
Details:rtrim()Function Syntax:string rtrim ( string $str [, string $character_mask ] )
Rtrim-removes white spaces (or other characters) at the end of a string)
Experience:
This is just for this demand!
Note:After the preceding method is used to operate a string, the operation result is returned and the string itself is not changed! Remember to use a variable to receive results!
Iii. Summary
The above is a summary of several methods for deleting the last character of a string in PHP. Have you learned this? I hope this article will help you in your study or work.