phpcharacter-encodingwhitespace

Trim whitespace ASCII character "194" from string


Recently ran into a very odd issue where my database contains strings with what appear to be normal whitespace characters but are in fact something else.

For instance, applying trim() to the string:

"TEST "

is getting me:

"TEST "

as a result. So I copy and paste the last character in the string and:

echo ord(' ');
194

194? According to ASCII tables that should be . So I'm just confused at this point. Why does this character appear to be whitespace and how can I trim() characters like this when trim() fails?


Solution

  • You can try with :

    PHP trim

    $foo = "TEST ";
    $foo = trim($foo);
    

    PHP str_replace

    $foo = "TEST ";
    $foo = str_replace(chr(194), '', $foo);
    

    IMPORTANT: You can try with chr(194).chr(160) or '\u00A0'

    PHP preg_replace

    $foo = "TEST ";
    $foo = preg_replace('#(^\s+|\s+$)#', '', $foo);
    

    OR (i'm not sure if it will work well)

    $foo = "TEST ";
    $foo = preg_replace('#[\xC2\xA0]#', '', $foo);