How to replace decoded Non-breakable space (nbsp)

Grzegorz picture Grzegorz · Nov 21, 2016 · Viewed 16k times · Source

Assuming I have a sting which is "a s d d" and htmlentities turns it into
"a s d d".

How to replace (using preg_replace) it without encoding it to entities?

I tried preg_replace('/[\xa0]/', '', $string);, but it's not working. I'm trying to remove those special characters from my string as I don't need them

What are possibilities beyond regexp?

Edit String I want to parse: http://pastebin.com/raw/7eNT9sZr
with function preg_replace('/[\r\n]+/', "[##]", $text)
for later implode("</p><p>", explode("[##]", $text))

My question is not exactly "how" to do this (since I could encode entities, remove entities i don't need and decode entities). But how to remove those with just str_replace or preg_replace.

Answer

David Ferenczy Rogožan picture David Ferenczy Rogožan · Nov 21, 2016

The problem is that you are specifying the non-breakable space in a wrong way. The proper code of the non-breakable space in UTF-8 encoding is 0xC2A0, it consists of two bytes - C2 (194) and A0 (160), you're specifying only the half of the character's code.

You can replace it using the simple (and fast) str_replace or using a more flexible regular expression, depending on your needs:

// faster solution
$regular_spaces = str_replace("\xc2\xa0", ' ', $original_string);

// more flexible solution
$regular_spaces = preg_replace('/\xc2\xa0/', ' ', $original_string);

Note that in case of str_replace, you have to use double quotes (") to enclose the search string because it doesn't understand textual representation of character codes so it needs those codes to be converted into actual characters first. That's made automatically by PHP because strings enclosed in double quotes are being processed and special sequences (e.g. newline character \n, textual representation of character codes, etc.) are replaced by actual characters (e.g. 0x0A for \n in UTF-8) before the string value is being used.

In contrast, the preg_replace function itself understands textual representation of the character codes so you don't need PHP to convert them into actual characters and you can use apostrophes (single quotes, ') to enclose the search string in this case.

The UTF-8 encoding is so called variable width character encoding, that means character codes consist from one up to four (8 bit) bytes. In general, more frequently used characters have shorter codes while more exotic characters have longer codes.