Regex to replace multiple spaces

Normally I just don’t worry about this since I’m usually building websites and HTML takes care of merging multiple spaces. But it comes up occasionally. And since it’s just a quick regex replace, it’s pretty quick to merge multiple spaces.

$x = preg_replace('/\s{2,}/m', ' ', "This     string   has     spaces");

Piece of cake.

It looks for any places that there is 2 or more spaces and replaces it with a single space.


This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

One Response to Regex to replace multiple spaces

  1. Ryan says:

    Oops, had to fix a typo. Switched to the m modifier instead of g.