PHP Replace Multiple Spaces, Dashes or Hyphens with Single One

Published on July 1, 2021 34 sec read

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:

<?php
$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:

<?php
$string="a----quick--brown------fox";

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

echo $solution1;
echo "<br>";
echo $solution2;
?>
That’s it. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write article on Laravel, Linux server, modern JavaScript and more on web development.

Follow