Remove Unicode Zero Width Space PHP

✔ Recommended Answer


$newBody = str_replace("​", "", $newBody);

presumes the text is HTML entity encoded. This:

$newBody = str_replace("\xE2\x80\x8C", "", $newBody);

should work if the offending characters are not encoded, but matches the wrong character (0xe2808c). To match the same character as #8203; you need 0xe2808b:

$newBody = str_replace("\xE2\x80\x8B", "", $newBody);


Answered By: Jef

Method #2

To remove Unicode zero width space (ZWSP) from a string in PHP, you can use the str_replace() function to replace the ZWSP character with an empty string. Here's an example:

$str = "Hello​ World"; // Contains ZWSP after "Hello" // Replace ZWSP with an empty string $str = str_replace("\u{200B}", "", $str); echo $str; // Outputs "Hello World" without ZWSP

In this example, the str_replace() function is used to replace the ZWSP character (represented by the Unicode code point \u{200B}) with an empty string. The resulting string, without the ZWSP, is then echoed to the output.

Note that the ZWSP character is not visible in most text editors or on most displays, so it can be difficult to spot in a string. If you suspect that a string contains ZWSP characters, you can use a Unicode character inspector tool to check.


Most Popular

PhpStorm, return value is expected to be 'A', 'object' returned

Laravel file upload returns forbidden 403, file permission is 700 not 755