PHP中字符串替换时导致的乱码

 文件chinese.php本身是utf8编码。
chinese.php
<?php
define('l', "<br />\n");
$f = $_REQUEST['f'];
function_exists($f) || die("Function $f not exists");
$f();

//========================================
function test1() {
    header("Content-type: text/html; charset=gbk");
    $finalStr = '中国,3';
    $finalStr = iconv('UTF-8', 'GBK', $finalStr);
    echo $finalStr . l;
    $finalStr = str_replace(',', ',', $finalStr);
    echo $finalStr . l;
}
//========================================


//========================================
function test2() {
    header("Content-type: text/html; charset=utf-8");
    $finalStr = '中国,3';
    echo $finalStr . l;
    $finalStr = str_replace(',', ',', $finalStr);
    echo $finalStr . l;
}
//========================================

//========================================
function test3() {
    header("Content-type: text/html; charset=utf-8");
    $finalStr = 'chinese,3';
    $finalStr = iconv('UTF-8', 'GBK', $finalStr);
    echo $finalStr . l;
    $finalStr = str_replace(',', ',', $finalStr);
    echo $finalStr . l;
}
//========================================
?>

1.测试一
http://localhost/research/chinese.php?f=test1
中国,3
中国锛?

2.测试二
http://localhost/research/chinese.php?f=test2
中国,3
中国,3

3.测试三
http://localhost/research/chinese.php?f=test3
chinese,3
chinese,3

4.总结
根据以上的测试,可以得出如下的结论:

function test1:
由于刚开始"中国,3"是utf8编码,且里面的内容含有中文,后面通过iconv转换成了gbk编码,而str_replace(',', ',', $finalStr);中,是全角逗号,可以理解为中文,而且是utf8编码的中文,由于”中国,3“已经转换成了gbk编码,全角逗号是utf8编辑,因此替换的时候出现了乱码

function test2:
“中国,3”与“,”均是utf8编码,因此进行str_replace操作后没有导致乱码。

function test3:
“chinese,3”是数字、字母及,(逗号),不管转换成什么编码还是原来的内容,尽管str_replace(',', ',', $finalStr);中是全角逗号,可以理解为中文,但是由于”chinese,3“中没有中文,所以替换后没有导致乱码,只能这样理解了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章