PHP Replace Multiple Spaces, Dashes or Hyphens with Single One

Hello artisans, sometimes we need to replace multiple spaces, hyphens with single space, hyphen or any character. In this short article, we are going to see the best way to do it. Let’s see:

Table of Contents

  1. Replace Spaces
  2. Replace Dashes/Hyphens

Replace Spaces

We’ll use preg_replace() to replace a pattern. If you don’t understand regular expressions, please take a look at this website.

Have a look at the example:

$string="a    quick  brown     fox";
$solution1 = preg_replace('/\s{2,}/',' ',$string);
$solution2 = preg_replace('/\s+/', ' ', $string);

echo $solution1;
echo "
"; echo $solution2; ?>

Replace Dashes/Hyphens

We already seen how to replace multi spaces with one spcae. Like that we can now replace anything. Let’s replace hyphens:


$solution1 = preg_replace('/-{2,}/','-',$string);
$solution2 = preg_replace('/-+/', '-', $string);

echo $solution1;
echo "<br>";
echo $solution2;

That’s it. Thanks for reading.