4.7.7 Trimming whitespace: trim(), ltrim(), and rtrim()This is NOT the latest copy of this book; click here for the latest version.
string trim ( string source [, string charlist])
string ltrim ( string source [, string charlist])
string rtrim ( string source [, string charlist])
Trim() is a function to strip whitespace from either side of a string variable, with "whitespace" meaning spaces, new lines, and tabs. That is, if you have the string " This is a test " and pass it to trim() as its first parameter, it will return the string "This is a test" - the same thing, but with the spaces trimmed off the end.
You can pass an optional second parameter to trim() if you want, which should be a string specifying the characters you want it to trim(). For example, if we were to pass to trim the second parameter " tes" (that starts with a space), it would output "This is a" - the test would be trimmed, as well as the spaces. As you can see, trim() is again case sensitive - the T in "This" is left untouched.
Trim() has two minor variant functions, ltrim() and rtrim(), which do the same thing but only trim from the left and right respectively.
Here are some examples:
<?php
$a = trim(" testing ");
$b = trim(" testing ", " teng");
$c = ltrim(" testing "); ?>
$a will result in "testing", $b will result in "sti", and $c will result in "testing " - as expected, and not surprising because trim() et al are simple to use.
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|