PHP replace space with dash explained with examples
Tags: webdev, beginners, php
Published: 2023-02-06 16:00:04

> ✋ **Update:** This post was originally published on my blog [decodingweb.dev](https://www.decodingweb.dev), where you can read the [latest version](https://www.decodingweb.dev/php-replace-space-with-dash) 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
<?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
```

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
<?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
```

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

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

// output: string(37) how
```

## 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
<?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
```

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
```

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
<?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, '-');
}
```

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

var_dump(makeSlug('PHP replace space with dash (with examples)'));
// output: string(41) php-replace-space-with-dash-with-examples
```

For a string with an existing dash:

```php
<?php

var_dump(makeSlug(' Generate a URL-friendly slug '));
// output: string(28) generate-a-url-friendly-slug
```

For string with an empty space at both ends:

```php
<?php

var_dump(slug(' PHP is fun! '));
// output: string(10) php-is-fun
```

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.