Also, if you're interpolating with heredocs, make sure to include appropriate spacing for the
whole string to appear properly. In the previous example, "Right now the time" has to include
a trailing space, and "but tomorrow it will be" has to include leading and trailing spaces.
1.8.4 See Also
For the syntax to interpolate variable variables (like
), see Recipe 5.5
documentation on the string concatenation operator at
Recipe 1.9 Trimming Blanks from a String
You want to remove whitespace from the beginning or end of a string. For example, you want
to clean up user input before validating it.
removes whitespace from the beginning
of a string,
from the end of a string, and
from both the beginning and
end of a string:
$zipcode = trim($_REQUEST['zipcode']);
$no_linefeed = rtrim($_REQUEST['text']);
$name = ltrim($_REQUEST['name']);
For these functions, whitespace is defined as the following characters: newline, carriage
return, space, horizontal and vertical tab, and null.
Trimming whitespace off of strings saves storage space and can make for more precise display
of formatted data or text within
tags, for example. If you are doing comparisons with
user input, you should trim the data first, so that someone who mistakenly enters "98052 " as
their Zip Code isn't forced to fix an error that really isn't. Trimming before exact text
comparisons also ensures that, for example, "salami\n" equals "salami." It's also a good idea
to normalize string data by trimming it before storing it in a database.
functions can also remove user-specified characters from strings. Pass the
characters you want to remove as a second argument. You can indicate a range of characters
with two dots between the first and last characters in the range.
// Remove numerals and space from the beginning of the line
print ltrim('10 PRINT A$',' 0..9');
// Remove semicolon from the end of the line
print rtrim('SELECT * FROM turtles;',';');