Skip to content

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.

Published inProgramming

One Comment

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

Leave a Reply

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