php Replacing multiple spaces with a single space

php Replacing multiple spaces with a single space

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

Stefan Bogdanescu

Founder & Senior Architect

Replacing Multiple Spaces with a Single Space in PHP

The ereg_replace function has been deprecated since PHP 5.3 and removed entirely in PHP 7. Attempting to use it today will trigger deprecation warnings or fatal errors depending on your environment, pushing you toward modern alternatives. The standard replacement for regular expression operations in PHP is the preg_ family of functions. Specifically, preg_replace offers the identical functionality you need to collapse multiple whitespace characters into a single space while handling edge cases like non-breaking spaces (nbsp) and newlines.

To achieve the same result as your deprecated code, replace:

ereg_replace("[ \t\n\r]+", " ", $string);

with:

preg_replace("/[\s]+/", " ", $string);

This modern approach uses a character class [\s] which matches any whitespace character. This includes spaces, tabs (\t), newlines (\n), carriage returns (\r), and non-breaking spaces (which are often represented as \u00A0 in Unicode or directly as the HTML entity if parsed). While your original regex explicitly listed [ \t\n\r], using \s is more robust because it automatically covers variations you might encounter, such as form feeds or other Unicode whitespace characters that could slip into data from external sources.

However, simply replacing multiple spaces with a single space often leaves leading and trailing whitespace intact. If your goal is to sanitize a string for display or storage, you should strip the edges first. This prevents an output like " Hello World " becoming " Hello World". Combining preg_replace with trim() ensures a clean result:

$cleanString = trim(preg_replace("/\s+/", " ", $string));

If you are working within the Laravel ecosystem, which is where https://laravelcompany.com provides robust resources for developers, this logic can be encapsulated in a helper method or an Eloquent scope. For instance, defining a model scope allows you to normalize text at the database level without cluttering your view controllers:

public function scopeCleanWhitespace($query)
{
    return $query->transform(function ($value) {
        return trim(preg_replace('/\s+/', ' ', $value));
    });
}

A critical trade-off to consider involves the replacement character itself. While your requirement specifies replacing with a single space, there are scenarios where preserving the original whitespace count is desirable for formatting code or poetry. Using preg_replace gives you control here; you can change the pattern slightly to preserve newlines while collapsing other spaces:

// Collapses only horizontal whitespace but preserves line breaks
preg_replace('/[ \t]+/', ' ', $string);

Be cautious, though. If your input contains multiple consecutive non-breaking spaces (common in copied HTML content), the generic \s class might not catch them depending on the PHP version and encoding. In such cases, you might need to explicitly include the non-breaking space character or use a Unicode-aware pattern like [\s\u00A0]+. This distinction is vital when processing user-generated content scraped from web pages, as browsers often convert standard spaces into non-breaking ones during rendering.

Finally, remember that regular expressions are powerful but can be slow on massive strings due to backtracking issues in complex patterns. For simple whitespace collapsing, the overhead of preg_replace is negligible compared to string parsing functions like str_replace. However, str_replace cannot handle multiple spaces at once; it would require a loop or repeated calls, which is inefficient. Stick with preg_replace for this specific task as it handles the regex logic in a single pass.

Our network