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

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

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

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

When you need to transform a string like $string = "this is my string"; into "thisismystring", the immediate instinct might be to use str_replace. While that function works, it introduces unnecessary overhead by treating space as just another character. A more efficient approach targets whitespace directly using built-in functions designed for pattern replacement or regex manipulation.

The most straightforward method for removing only standard spaces (ASCII 32) is str_replace. You can pass a string of spaces and the target string to this function:

$string = "this is my string";
$cleaned = str_replace(' ', '', $string);
// Result: "thisismystring"

This approach is predictable and fast for static whitespace. However, it fails if your input contains tabs, newlines, or multiple consecutive spaces. If you are dealing with user-generated content, relying solely on a literal space character can lead to inconsistent results where some whitespace remains untouched.

For scenarios requiring the removal of any kind of whitespace—including tabs, carriage returns, and non-breaking spaces—the preg_replace function offers greater flexibility. You can use the regex pattern \s+, which matches one or more horizontal or vertical whitespace characters:

$string = "this  is\tmy\nstring"; // Includes multiple spaces, a tab, and a newline
$cleaned = preg_replace('/\s+/', '', $string);
// Result: "thisismystring"

This method consolidates all whitespace variations into a single operation. It also handles cases where spaces are used for indentation or line breaks that you want to collapse entirely. The cost here is the slight overhead of compiling and executing a regular expression, which might matter in extremely tight performance loops, though it remains negligible for typical application logic.

Performance Considerations

If you are processing millions of strings in a high-throughput environment, the difference between str_replace and preg_replace becomes measurable. Simple string replacement avoids the regex engine entirely, making it faster when you only need to strip literal spaces. Conversely, if your data is messy and contains mixed whitespace types, preg_replace prevents you from needing multiple passes or chaining functions.

Another consideration is memory usage. Creating a large string of space characters for str_replace on massive inputs consumes more memory than passing a regex pattern directly to preg_replace. In most web application contexts, this trade-off is irrelevant, but it is worth noting when optimizing resource-constrained environments.

Handling Edge Cases

A common pitfall occurs when dealing with Unicode-specific spaces, such as the non-breaking space (NBSP) often found in text copied from Word documents or legacy systems. These characters are not matched by \s in some regex configurations unless explicitly handled, and they certainly aren't matched by a simple str_replace(' ', ...).

To handle these robustly, you might combine approaches or use a broader character class in your regex:

// Removes standard spaces, tabs, newlines, NBSP (U+00A0), etc.
$cleaned = preg_replace('/\s+/', '', $string); 
// Note: In some contexts, \s might not match NBSP without the /u modifier or specific flags depending on PHP version and PCRE settings.

If you are building a utility library for data normalization, it is safer to rely on preg_replace with the /u flag (Unicode mode) when working with internationalized text:

$cleaned = preg_replace('/\s+/', '', $string, null, $count); 
// Using the count parameter can help you debug if matches are occurring unexpectedly.

When to Use Which

Choose str_replace for performance-critical paths where input is guaranteed to be clean and contains only standard ASCII spaces. It requires no regex engine initialization and executes at native C speed. Opt for preg_replace when dealing with untrusted data, legacy imports, or complex formatting requirements where whitespace types vary.

Both methods are standard in the PHP ecosystem. If you are looking for further optimization techniques or need to strip spaces from arrays of strings, wrapping these functions in a helper utility is a common pattern to keep your core logic clean and readable.

Our network