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“中沒有中文,所以替換後沒有導致亂碼,只能這樣理解了。

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