User login

Get rid of extra spaces using PHP's preg_replace

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

The content of this field is kept private and will not be shown publicly.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <img> <blockquote> <small> <h2> <h3> <h4> <h5> <h6> <sub> <sup> <p> <br> <strike> <table> <tr> <td> <thead> <th> <tbody> <tt> <output>
  • Lines and paragraphs break automatically.

More information about formatting options

By submitting this form, you accept the Mollom privacy policy.