Guide to simple use of trim () functions in PHP
String trim (string $ str [, string $ charlist])-removes spaces (or other characters) at the beginning and end of the string)
When the second parameter of the trim () function is null, spaces, tabs, line breaks, carriage returns, and vertical tabs are removed by default. When the second parameter is added
The Code is as follows:
1) trim ('\ "string \"', '\ "sg'); // final output: \" strin
2) trim ('\ "string \"', '\ "sg'); // final output: \" string \"
2) trim ('\ "string \"', '\ "sg'); // The final output is trin.
Therefore, the trim () function preferentially removes the spaces at the beginning and end of a character, and then filters out the given characters (lists) to be removed. This function is also applicable to the ltrim () and rtrim () functions.
Definition and usage
The PHP function trim () removes spaces and other predefined characters from both ends of the string.
Syntax
Trim (str, charlist) parameter 1 str is the string to be operated, parameter 2 charlist (optional) specifies the special symbol to be removed.
If the second parameter is not set to a value, the following characters are removed by default:
"" (ASCII 32 (0x20), an ordinary space.
"\ T" (ASCII 9 (0x09), a tab.
"\ N" (ASCII 10 (0x0A), a new line (line feed ).
"\ R" (ASCII 13 (0x0D), a carriage return.
"\ 0" (ASCII 0 (0x00), the NUL-byte.
"\ X0B" (ASCII 11 (0x0B), a vertical tab.
If you want to remove other characters, you can set them in the second parameter.
Example 1
1 2 3 4 5 6 7 |
<? Php $ Str = "Remove blank characters at both ends of the string using the trim function "; $ Str1 = trim ($ str ); Echo "before processing". strlen ($ str). "characters"; echo "<br/> "; // Www.phpjc.cn echo "<br/> "; Echo "after processing with the trim function". strlen ($ str1). "characters "; ?> |
Output:
39 characters before processing 34 characters after being processed using the PHP function trim ()
Example 2
1 2 3 4 5 6 7 |
<? Php $ Str = "## remove specific characters at both ends of the string using the trim function ####"; $ Str1 = trim ($ str ,"#"); // Input the second parameter for the trim function, Trim will delete the # character echo $ str at both ends of the string $ str. "<br> "; Echo $ str1; ?> |
Output:
# Use the PHP function trim () to remove specific characters at both ends of the string ### use the function trim to remove specific characters at both ends of the string