PHP tip: Trimming excess whitespace


Excess whitespace is a constant problem when working with form data. The

function is usually the first tool a programmer turns to, because it removes any excess spaces from the beginning or end of a string. For example, " Wicked Cool PHP " becomes "Wicked Cool PHP." In fact, it's so handy that you may find yourself using it on almost every available piece of user-inputted, non-array data:

$user_input = trim($user_input);

But sometimes you have excessive whitespace inside a string -- when someone may be cutting and copying information from an email, for instance. In that case, you can replace multiple spaces and other whitespace with a single space by using the preg_replace() function. The reg stands for regular expression, a powerful form of pattern matching.

function remove_whitespace($string) {
$string = preg_replace('/\s+/', ' ', $string);
$string = trim($string);
return $string;

You'll find many uses for this script outside of form verification. It's great for cleaning up data that comes from other external sources.


Today's Tip was adapted from "Wicked Cool PHP" by William Steinmetz with Brian Ward, Published by No Starch Press.
Free Course: JavaScript: The Good Parts
View Comments
You Might Like
Join the discussion
Be the first to comment on this article. Our Commenting Policies