Home ›
Get rid of extra spaces using PHP's preg_replaceGet rid of extra spaces using PHP's preg_replace
Submitted by Benjamin Melançon on April 20, 2009 - 9:21pm
Right there in the examples for the php function preg_replace was how to strip whitespace from a string:
<?php
$str = preg_replace('/\s\s+/', ' ', $str);
?>
Ereg replace looks prettier:
<?php
$string = trim(ereg_replace(' +', ' ', $string));
?>
However, Agaric has read in several places that preg_replace tends to be faster.
Resolution
Searched words:
preg replace multiple spaces with one
strip white space
remove extra blank spaces with Perl RegEx
Comments
Be aware, however, that
Be aware, however, that ereg_replace is depreciated and is eliminated in php6:
Better to use preg_replace for forward-compatibility.
Why not use
Why not use trim(preg_replace('/\s\s+/', ' ', $str)); ??? (at least, to be comparable to the ereg statement)
you got it bit wrong
the proper formula is
$str = preg_replace('/\s+/', ' ', $str);
the \s in your '\s\s+/' is unnecessary - \s+ allready says "one or more" and in your version, you will not replace single space-chars e.g. tabs and other non-space characters matched with \s with your standard ' ', what you probably do not want
Post new comment