Friday, November 26, 2010

How to replace multiple spaces from a string in PHP

This snippet is useful when you need to replace multiple spaces from a string. Tabs, New Lines and Carriages are also replaced.

<?php
function replace_multiple_spaces($string)
{
    // tabs, new lines and carriages are also replaced
$string = ereg_replace("[ \t\n\r]+", " ", $string);

return $string;
}

$string = "This
   is
a   dummy
text. ";

$new_string = replace_multiple_spaces($string);

// Outputs: This is a dummy text
echo $new_string;
?>

No comments:

Post a Comment