Manipulating Strings with PHP

PHP provides many functions that will transform a string argument, subtly or radically, as you'll soon see.

Cleaning Up a String with trim() and ltrim() and strip_tags()

When you acquire text from the user or a file, you can't always be sure that you haven't also picked up white space at the beginning and end of your data. The trim() function shaves any white space characters, including newlines, tabs, and spaces, from both the start and end of a string. It accepts the string to be modified, returning the cleaned-up version.

$text = "\t\tlots of room to breathe      ";
echo "<pre>$text</pre>";
// prints "              lots of room to breathe      ";
$text = trim($text);
echo "<pre>$text</pre>";
// prints "lots of room to breathe";

Get Sams Teach Yourself PHP, MySQL® and Apache All in One now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.