Removing Excess Whitespace Inside a String

Monday, March 30, 2009

One of constant problems when working with form data is excess whitespace. 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, " codeaway php " becomes "codeaway php". 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.
<?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.

Hope it helps.

0 comments: