# PHP Remove All Spaces from a String with str_replace

> Use str_replace() to remove spaces or preg_replace() with a regex pattern to strip all whitespace including tabs and line breaks from a PHP string

**URL:** https://sentry.io/answers/how-do-i-strip-all-spaces-out-of-a-string-in-php/

---

## The Problem

How do I strip all spaces out of a string in PHP?

## The Solution

To remove the spaces from a string in PHP, use the `str_replace()` function. Use a space `' '` as the first argument, an empty string `''` as the second argument, and the string as the third argument. For example:

```php
$string = 'This string might have spaces.';
$strippedString = str_replace(' ', '', $string);

echo $strippedString;
```

This returns the original string with spaces removed:

```
Thisstringmighthavespaces
```

If you want to remove all whitespace from a string, including tabs and line breaks, you can use the `preg_replace()` function. Pass in the `'/\s+/'` regular expression, followed by an empty string `''`, and the actual string variable. For example:

```php
$string = "This string may contain   tabs, spaces, and even a\nlinebreak.";
$strippedString = preg_replace('/\s+/', '', $string);

echo $strippedString;
```

Output:

```
Thisstringmaycontaintabs,spaces,andevenalinebreak.
```

---

*Source: [sentry.io/answers/how-do-i-strip-all-spaces-out-of-a-string-in-php/](https://sentry.io/answers/how-do-i-strip-all-spaces-out-of-a-string-in-php/)*
