DEV Community

Cover image for PHP replace space with dash explained with examples
Reza Lavarian
Reza Lavarian

Posted on • Originally published at decodingweb.dev

PHP replace space with dash explained with examples

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

If you want to “replace space with dash” in PHP, you can do so with the str_replace() function. We usually replace spaces with dashes to generate a URL-friendly slug from a given string, but you might need them for other purposes.

The str_replace() function accepts three arguments, search, replace, and subject, and replaces all occurrences of the search string (from subject) with replacement string.

Let’s start with a simple example:

<?php

$title =  'How to replace space with dash in PHP';
$slug = str_replace(' ', '-', $title);
var_dump($slug);

// output: string(37) How-to-replace-space-with-dash-in-PHP
Enter fullscreen mode Exit fullscreen mode

In the above example, all spaces are replaced with dashes (a.k.a hyphen).

If you need to make the string lowercase, you can use the strtolower() function like so:

<?php
$title =  'How to replace space with dash in PHP';
$slug = str_replace(' ', '-', strtolower($title));
var_dump($slug);

// output: string(37) how-to-replace-space-with-dash-in-php
Enter fullscreen mode Exit fullscreen mode

If you want to reverse a dash-separated string back to a title, you can swap replace and search values:

<?php
$slug =  'how-to-replace-space-with-dash';
$title = str_replace('-', ' ', $slug);
var_dump($slug);

// output: string(37) how
Enter fullscreen mode Exit fullscreen mode

A better approach to "replace space with dash" in URL slugs

Replacing spaces with dashes are quick and easy with the str_replace() function. However, if you need more control over the result, like excluding non-alphanumeric characters (e.g., (, ), $) or double dashes, you should use regular expressions.

And to use regular expressions, you need to use preg_match() instead of str_replace().

Let's see a quick example:

<?php
function makeSlug($title) {
    return preg_replace('![\s]+!u', '-', strtolower($title));
}

$slug = makeSlug('PHP replace space with dash');
var_dump($slug);

// output: string(27) php-replace-space-with-dash
Enter fullscreen mode Exit fullscreen mode

For those new to regular expressions, the two exclamation marks (!) define the beginning and the end of our regex; They can be any character as long as they are the same. The u at the end is to support Unicode characters.

!<EXPRESSION>!u
Enter fullscreen mode Exit fullscreen mode

This preg_replace() call replaces every space (\s) with a dash.

So far, it works just like str_replace().

Now, let's add two more regexes to the function. One is to remove characters that aren't hyphens, digits, or letters. And another to remove double dashes (in case the string already contains dashes).

<?php

function makeSlug($title) {
    $title = preg_replace('![\s]+!u', '-', strtolower($title));
    $title = preg_replace('![^-\pL\pN\s]+!u', '', $title);
    $title = preg_replace('![-\s]+!u', '-', $title);

    return trim($title, '-');
}
Enter fullscreen mode Exit fullscreen mode

As you can see, we also use trim() to remove any hyphens off the beginning or end of the string.

Let's try out the function.

For strings with non-alphanumeric chars:

<?php

var_dump(makeSlug('PHP replace space with dash (with examples)'));
// output: string(41) php-replace-space-with-dash-with-examples
Enter fullscreen mode Exit fullscreen mode

For a string with an existing dash:

<?php

var_dump(makeSlug(' Generate a URL-friendly slug '));
// output: string(28) generate-a-url-friendly-slug
Enter fullscreen mode Exit fullscreen mode

For string with an empty space at both ends:

<?php

var_dump(slug(' PHP is fun! '));
// output: string(10) php-is-fun
Enter fullscreen mode Exit fullscreen mode

This handy function is inspired by Laravel's implementation of the Str::slug() method.

All right, I think it does it! I hope you could find this guide helpful.

Thanks for reading.

Latest comments (0)