Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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"
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page