How to replace decoded Non-breakable space (nbsp)

How to replace decoded Non-breakable space (nbsp)

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

Stefan Bogdanescu

Founder & Senior Architect

How to replace decoded Non-breakable space (nbsp)

When working with HTML content in PHP, a common friction point involves handling entities generated by functions like htmlentities(). If you pass a string containing non-breaking spaces ( ) back through that function without care, the literal text   becomes encoded again. However, there is often a need to strip these specific characters while leaving other content intact. A frequent misconception is that simply replacing the decoded HTML entity string with an empty value using str_replace() or preg_replace() will work directly on a raw string buffer.

In reality, the character sequence   represents an entity, but if your source data already contains the literal characters &, n, b, s, and p, you might be looking at two different problems: removing the entity syntax from a decoded string versus removing the actual Unicode non-breaking space character (U+00A0) that sometimes leaks through or gets inserted.

If your input is already a raw PHP string containing the literal text  , and you want to remove them without re-encoding, a simple str_replace is technically sufficient for this specific case:

$string = 'a s d d';
$cleanString = str_replace(' ', '', $string);
echo $cleanString; 
// Output: "a s d d"

However, you mentioned trying preg_replace('/[\xa0]/', '', $string) and finding it ineffective. This is a classic case of mixing character encodings in your mental model versus your actual string data. The byte sequence \xa0 represents the actual non-breaking space character (NBSP). If your string contains the literal text  , searching for the binary byte 0xA0 will yield no matches because the characters are ASCII-based (&, n, etc.), not the NBSP byte itself.

If you specifically need to remove the actual Unicode non-breaking space character (often inadvertently introduced by copy-pasting from Word documents or certain web scrapers) rather than the HTML entity text, you must target the correct byte or code point. In PHP, you can use preg_replace with a Unicode-aware pattern:

$string = 'a\xa0s\xa0d\xa0d'; // String containing actual NBSP characters
$cleanString = preg_replace('/\x{A0}/u', '', $string);
echo $cleanString; 
// Output: "a s d d"

Note the use of \x{A0} with the u flag. This ensures PHP treats the pattern as a Unicode code point, matching the actual NBSP character regardless of the current script encoding context. Without the u modifier or the specific hex representation, preg_replace might interpret the sequence differently depending on your system's default encoding (e.g., UTF-8 vs. Windows-1252).

Why Regular Expressions Can Be Tricky Here

Regular expressions are powerful but can introduce overhead when dealing with simple string substitutions. If you have a massive amount of text where performance is critical, str_replace is generally faster because it operates on C-level string functions without the regex engine's parsing overhead. However, if your goal is to remove NBSPs that might be represented in various encodings (e.g., sometimes as  , sometimes as \xa0, and sometimes as a zero-width space), a single regex can cover multiple bases:

// Removes both the literal entity text and the actual NBSP character
$string = preg_replace('/&(?:nbsp;|NBSP;)/i | \x{A0}/u', '', $string);

This pattern handles the text-based entity case (case-insensitive) and the binary character case simultaneously. Be cautious, though: regex patterns that try to handle too many variations can become brittle. If you encounter   inside an attribute value or within a JavaScript block, blindly stripping it might break your HTML structure if not done carefully.

The Safer Alternative: Decode First

While the prompt asks for solutions using only str_replace or preg_replace, experienced engineers often advocate for a slightly more robust approach involving decoding. If you are unsure whether the string contains entities or raw characters, decoding them first normalizes the data.

Using html_entity_decode():

$string = 'a s d d';
$decoded = html_entity_decode($string); 
// Result: "a s d d" (assuming UTF-8 encoding)

This converts   into the actual NBSP character (\xa0). Once decoded, you can then apply your specific cleaning logic. If your downstream system expects raw ASCII spaces and not NBSPs, this two-step process ensures consistency. It avoids the risk of missing an NBSP entity because you are handling the semantic meaning of the data rather than just matching byte patterns.

Performance and Encoding Considerations

When choosing between str_replace and preg_replace, consider the encoding of your input. If your application runs in a mixed-encoding environment (common in legacy systems), relying on \x{A0} inside a regex without explicitly setting the internal encoding to UTF-8 can lead to silent failures where characters are misinterpreted as multiple bytes. Always ensure mb_internal_encoding('UTF-8') is set if you are dealing with internationalized content.

Finally, remember that stripping non-breaking spaces changes the semantic meaning of your text for some readers and screen readers, which rely on them for line breaks or distinct word separation. Only strip them if your downstream consumer explicitly requires standard spaces (U+0020). If you need to preserve layout but just change the character type, consider replacing with a standard space instead:

$cleanString = preg_replace('/\x{A0}/u', ' ', $string);

This preserves word boundaries while ensuring compatibility with systems that do not handle NBSPs well.

Our network