4

I have a weird whitespaces in string, white spaces are not white spaces. I have a problem with converting them with regex and str_replace i.e.

echo str_replace(' ','_',$string);

any ideas how to fix it? utf8_encode is also not working, regex \s either, when you copy this text to Notepad++ it shows as

Ê    

instead of white space.

What I am trying to achieve is to run this regex

preg_replace('/[^a-z0-9 ]/i','',$string) 

but since those 'whitespaces' are not a whitespaces they are being removed as well.

6
  • What language are you working in? All I can tell is that it's something with str_replace and utf8_encode functions... Commented Aug 31, 2011 at 20:03
  • 1
    Could it be because of Notepad++ conversion problem instead of UTF8 PHP?
    – Tarik
    Commented Aug 31, 2011 at 20:08
  • nope, php is not handling it, the use of notepad is simply to see if its whitespace or some other character, when trying to convert to utf8 in notepad it displays \xCA instead
    – Marcin
    Commented Aug 31, 2011 at 20:11
  • Notepad++ probably incorrectly detects the incorrect character encoding for that character. There's no easy way in PHP to replace all unicode characters in a string that could be considered some form of whitespace (there's many). If your target string does not support whitespace (such as urls for instance) it's actually probably more likely that there's many other characters that are not acceptable. I think if you explain what you're actually trying to achieve, there may be a different solution possible
    – Evert
    Commented Aug 31, 2011 at 20:11
  • what I am trying to achieve is to run this regex preg_replace('/[^a-z0-9 ]/i','',$string) but since those 'whitespaces' are not a whitespaces they are being removed as well
    – Marcin
    Commented Aug 31, 2011 at 20:14

1 Answer 1

4

I think I got it, from PHP site:

You might wonder why

trim(html_entity_decode(' '));    

doesn't reduce the string to an empty string, that's because the ' ' entity is not ASCII code 32 (which is stripped by trim()) but ASCII code 160 (0xa0) in the default ISO 8859-1 characterset.

3
  • 1
    No, the trick is to do /\xA0/u. Only ever deal with Unicode characters, not with serializations.
    – tchrist
    Commented Aug 31, 2011 at 21:22
  • Exactly. nbsc stands for non breaking space. It is not considered whitespace.
    – Phil
    Commented Nov 17, 2015 at 22:42
  • 1
    At HeavyDots we wrote a FUNNY post about the "strange white space" and we provided both a tool to crawl a URL and detect it and a technique we used to find and replace it in PHP. Drop by and check it out! ;-) heavydots.com/blog/when-the-white-space-became-a-beast Commented Jan 5, 2017 at 4:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.