PHP tip: Trimming excess whitespace

RELATED TOPICS

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.

\<\?php
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.

_________________

wicked-cool-php_cov-90.jpg
Today's Tip was adapted from "Wicked Cool PHP" by William Steinmetz with Brian Ward, Published by No Starch Press.
RELATED TOPICS
What’s wrong? The new clean desk test
View Comments
You Might Like
Join the discussion
Be the first to comment on this article. Our Commenting Policies