Posted by & filed under Programming.

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.

One Response to “Regex to replace multiple spaces”

Leave a Reply

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