PHP provides three useful functions to remove unnecessary white space from strings:
These functions trim white space before or after the text; any white space within the text itself is left intact.
All three functions work in the same way-they take the string to trim as an argument, and return the trimmed string:
<?php $myString = " this is a test! "; echo "|" . trim($myString) . "|\n"; // Displays "|this is a test!|" echo "|" . ltrim($myString) . "|\n"; // Displays "|this is a test! |"; echo "|" . rtrim($myString) . "|\n"; // Displays "| this is a test!|"; ?>// w w w . ja v a 2 s . co m
You can specify an optional second argument: a string of characters to treat as white space.
The function then trims any of these characters from the string, instead of using the default white space characters.
The white space includes
Character | Meaning |
---|---|
"" | space |
"\t" | tab |
"\n" | newline |
"\r" | carriage return |
"\0" | a null byte |
"\v" | vertical tab |
You can use ".." to specify ranges of characters (for example, "1..5" or "a..z").
Here's an example that strips line numbers, colons, and spaces from the start of each line of verse:
<?php $a1 = "1: this is a test\n"; $a2 = "2: this is a test.\n"; $a3 = "3: this is atest,\n"; echo ltrim($a1, "0..9: "); echo ltrim($a2, "0..9: "); echo ltrim($a3, "0..9: "); ?>//from w w w. j a v a 2 s .c o m