Replacing Spaces with Dashes in PHP Strings

Replacing spaces with dashes in strings is a common task in PHP web development.

Dashes can be useful for creating clean URLs, generating slugs, and more. In this tutorial, we will cover two easy methods to replace spaces with dashes using PHP built-in functions.

Why Replace Spaces with Dashes

There are a few key reasons you may want to replace spaces with dashes in a string:

  • Create SEO-friendly URLs. Dashes are commonly used in URLs instead of spaces.
  • Generate slugs. Slugs are URL-friendly versions of strings used for titles, tags, etc.
  • Improve readability. Dashes can separate words clearly without spaces.
  • Compatibility with systems that don’t allow spaces.

By swapping spaces for dashes, you can generate strings that work better for these purposes.

Using str_replace()

The simplest way to replace spaces with dashes is using str_replace():

$string = "replace whitespace with dash"; 
$output = str_replace(' ', '-', $string); 
echo $output; 

This replaces all space characters with a dash.


  • Simple and straight-forward syntax
  • Fast performance


  • Can cause extra dashes if there are multiple spaces

Using preg_replace()

For more control, you can use preg_replace() and regular expressions:

$string = "replace whitespace with dash"; 
$output = preg_replace('/(?<!\\s)\\s(?!\\s)/', '-', $string); 
echo $output; 

This regular expression will replace single spaces between words, but leave multiple spaces alone.


  • Handles extra whitespace
  • More control over what matches


  • More complex syntax

When to Use Each Approach

  • Use str_replace() for simple global find/replace cases.
  • Use preg_replace() if you need to match specific space patterns.

So in summary, str_replace() is easier, while preg_replace() is more precise. Choose the one that best meets your specific needs.


Replacing spaces with dashes in strings is useful for generating clean URLs, slugs, and more readable formats. Both str_replace() and preg_replace() can be used to swap spaces for dashes in PHP.

Use str_replace() for basic global replacements or preg_replace() when you require more control over the spaces matched. With the techniques covered here, you should have no problem dash-ifying strings in your PHP applications.

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment