PHP and character encoding problem with  character

我与影子孤独终老i 提交于 2020-01-14 10:46:27

问题


I'm having a problem where PHP (5.2) cannot find the character 'Â' in a string, though it is clearly there.

I realize the underlying problem has to do with character encoding, but unfortunately I have no control over the source content. I receive it as UTF-8, with those characters already in the string.

I would simply like to remove it from the string. strpos(), str_replace(), preg_replace(), trim(), etc. Cannot correctly identify it.

My string is this:

"Â  Â  Â  A lot of couples throughout the World "

If I do this:

$string = str_replace('Â','',$string);

I get this:

"� � � A lot of couples throughout the World"

I even tried utf8_encode() and utf8_decode() before the str_replace, with no luck.

What's the solution? I've been throwing everything I can find at it...


回答1:


I use this:

function replaceSpecial($str){
$chunked = str_split($str,1);
$str = ""; 
foreach($chunked as $chunk){
    $num = ord($chunk);
    // Remove non-ascii & non html characters
    if ($num >= 32 && $num <= 123){
            $str.=$chunk;
    }
}   
return $str;
} 



回答2:


$string = str_replace('Â','',$string);

How is this 'Â' encoded? If your script file is saved as iso-8859-1 the string 'Â' is encoded as the one byte sequence xC2 while the (/one) utf-8 representation is xC3 x82. php's str_replace() works on the byte level, i.e. it only "knows" single-byte characters.

see http://docs.php.net/intro.mbstring




回答3:


From the PHP Manual Comment Page:

http://www.php.net/manual/en/function.preg-replace.php#96847

And from StackOverflow:

Remove accents without using iconv



来源:https://stackoverflow.com/questions/3587383/php-and-character-encoding-problem-with-%c3%82-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!