Remove multiple whitespaces

Remove multiple whitespaces

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

Stefan Bogdanescu

Founder & Senior Architect

Stripping All Whitespace from Database Strings

Working with raw data directly pulled from a MySQL database often yields strings that are messy by default. When querying text fields, it is common to encounter records containing newlines (\n), tabs (\t), and irregular spacing between words. While this might be acceptable for specific log formats or code blocks, standard prose usually requires a clean, single-spaced representation.

The core challenge lies in distinguishing between the different types of whitespace characters and applying the correct logic to normalize them. A common misunderstanding is that \s in regular expressions only matches standard spaces. In reality, \s is a metacharacter designed to match any Unicode whitespace character, including newlines, carriage returns, tabs, form feeds, and non-breaking spaces.

The Flaw in the Initial Approach

A frequent attempt to solve this problem involves using preg_replace with a pattern that tries to find two or more consecutive whitespaces and replace them with a single space:

$row['message'] = preg_replace('/\s\s+/', ' ', $row['message']);

While this code snippet correctly collapses multiple spaces into one, it fails to handle the scenario where whitespace characters are not adjacent. For example, if you have a newline character followed immediately by a space ("\n "), or a tab followed by a newline ("\t\n"), the pattern \s\s+ will not match because it strictly requires at least two consecutive whitespace entities in a row. It treats isolated whitespace characters as valid separators rather than noise to be removed.

To truly normalize the string, you must target every instance of whitespace, regardless of whether it is preceded by another whitespace character or a non-whitespace character.

The Correct Pattern: \s+

The most robust solution involves changing the regex quantifier. Instead of looking for two or more spaces (\s\s+), you should look for one or more whitespace characters anywhere in the string (\s+).

Here is the corrected implementation:

$row['message'] = preg_replace('/\s+/', ' ', $row['message']);

In this pattern, \s+ matches a single space, a newline, a tab, or any combination thereof. The replacement string ' ' ensures that all of these variations are collapsed into a standard space character. If your goal is to strip whitespace entirely from the edges of the string as well (e.g., leading or trailing newlines), you might also consider wrapping this in trim() or using word boundaries, but usually, collapsing internal whitespace is the primary requirement for text normalization.

Handling Edge Cases and Performance

When working with large datasets, it is important to consider the performance implications of regex operations. While preg_replace is generally efficient enough for standard application logic, running this on millions of rows in a single batch operation could become a bottleneck. In such high-volume scenarios, applying this transformation in a database layer (using MySQL's REPLACE() function combined with REGEXP_REPLACE) or during the initial import process might be more performant than handling it in the application code for every request.

Another consideration is preserving intentional spacing. If your data structure relies on multiple spaces to indicate indentation (common in pre-formatted text blocks), blindly replacing all whitespace sequences could destroy the layout. In those specific cases, you should first check if the string contains markers like markdown code fences or HTML tags before applying a global normalization.

If you are building an application where this data cleaning happens frequently, consider creating a reusable helper function or extending your Eloquent model to cast these fields automatically. For instance, defining a custom accessor in Laravel allows you to clean the message attribute every time it is retrieved, ensuring consistency across your API responses without cluttering your controller logic.

For more complex text processing needs, such as handling HTML entities within the cleaned string, you may want to explore dedicated libraries like league/commonmark or stick to native PHP string functions if the regex approach proves sufficient for your specific use case.

Our network