Pages

Trimming Excess Whitespace

Excess whitespace is a constant problem when working with form data. The trim() 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 that you will see several times in this chapter.
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.