Name

trim()

Synopsis

    string trim ( string str [, string trim_chars] )

You can use the trim() function to strip spaces, new lines, and tabs (collectively called whitespace) from either side of a string variable. 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 surrounding spaces removed.

You can pass an optional second parameter to trim() if you want, which should be a string specifying the individual 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.

There are two minor variants to trim()—ltrim() and rtrim()—which do the same thing, but only trim from the left and right respectively.

Here are examples:

    $a = trim(" testing ");
    // $a is "testing"

    $b = trim(" testing ", " teng");
    // $b is is "sti"

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.