Return to Snippet

Revision: 7365
at July 19, 2008 11:17 by jamesming


Updated Code
<?php
$string = 'This string      has        no       whitespaces.';
echo ereg_replace( '  +', '', $string ); //note: before '+' we have 2 spaces
?>

Output: This string has no white spaces.

// OR EVEN BETTER

trim's code can of course be simplified with some use of the trim() function....

<?php
$str = "  Words with  lots      of  spaces    ";
$str = preg_replace('/\s\s+/', ' ', trim($str));
?>

Doing the trim() first reduces the workload being put on the more expensive preg_replace().

Revision: 7364
at July 19, 2008 11:15 by jamesming


Initial Code
<?php
$string = 'This string      has        no       whitespaces.';
echo ereg_replace( '  +', '', $string ); //note: before '+' we have 2 spaces
?>

Output: This string has no white spaces.

Initial URL
http://us3.php.net/trim

Initial Description


Initial Title
Converts big whitespaces into one whitespace

Initial Tags


Initial Language
PHP