Trimming whitespace

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:

    $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.


If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Wrapping your lines >>

Previous chapter: Returning the first occurrence of a string

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.