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
Searched words:
preg replace multiple spaces with one
strip white space
remove extra blank spaces with Perl RegEx
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
More like this
- PHP's Debug Backtrace Function
- Which is faster to check, Drupal's module_exists or PHP's function_exists?
- Drupal's .info file parser versus PHP's .ini file parser
- Locale subset module motivation: remove, hide, get rid of non-public UI strings
- One character patch to location module to get rid of senseless too many empty locations error


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)
Post new comment