Page 133 - Beginning PHP 5.3
P. 133
Chapter 5: Strings
Trimming Strings with trim(), ltrim(), and rtrim()
Often you find yourself working with text that you ’ ve received from an outside source, such as an
HTML form field or a text file. In these situations, the text can often contain unwanted white space at the
beginning or end of the text (or both). For example, a user might add newlines before or after text in a
text area field, or a text file might contain tabs for padding at the start of each line.
White space isn ’ t usually a problem for humans, but it can wreak havoc with a script that expects a
string to be of a certain length, or that is trying to compare one string to another. Fortunately, PHP
provides three useful functions to remove unnecessary white space from strings:
❑ trim() removes white space from the beginning and end of a string
❑ ltrim() removes white space only from the beginning of a string
❑ rtrim() removes white space only from the end of a string
Note that these functions only 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:
$myString = “ What a lot of space! “;
echo “ < pre > ”;
echo “|” . trim( $myString ) . “|\n”; // Displays “|What a lot of space!|”
echo “|” . ltrim( $myString ) . “|\n”; // Displays “|What a lot of space! |”;
echo “|” . rtrim( $myString ) . “|\n”; // Displays “| What a lot of space!|”;
echo “ < /pre > ”;
You can also 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 — which, incidentally, are “” (space), “\t” (tab), “\n” (newline), “\r” (carriage return), “\0”
(a null byte), and “\v” (vertical tab). You can also 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:
$milton1 = “1: The mind is its own place, and in it self\n”;
$milton2 = “2: Can make a Heav’n of Hell, a Hell of Heav’n.\n”;
$milton3 = “3: What matter where, if I be still the same,\n”;
echo “ < pre > ”;
echo ltrim( $milton1, “0..9: “ );
echo ltrim( $milton2, “0..9: “ );
echo ltrim( $milton3, “0..9: “ );
echo “ < /pre > ”;
This code displays:
The mind is its own place, and in it self
Can make a Heav’n of Hell, a Hell of Heav’n.
What matter where, if I be still the same,
95
9/21/09 8:53:47 AM
c05.indd 95
c05.indd 95 9/21/09 8:53:47 AM