PHP關於函數傳中文值亂碼的問題
想做一個遊戲啟用碼產生函數,寫出來之後發現個問題:$str放中文進去的時候出現亂碼,請問該怎麼解決一下?
function set_randcode($str, $num, $len, $mark) {
$strs_shuffle = str_shuffle((str_shuffle(strtoupper(trim($str))) . str_shuffle(strtoupper(trim($str))) . str_shuffle(strtoupper(trim($str)))));
$code = Array();
for ($i = 0; $i < $num*2; $i++) {
$code[] = (substr("$strs_shuffle", mt_rand(0, (strlen($str) - $len)), $len) . $mark . substr("$strs_shuffle", mt_rand(0, (strlen($str) - $len)), $len) . $mark . substr("$strs_shuffle", mt_rand(0, (strlen($str) - $len)), $len) . $mark . substr("$strs_shuffle", mt_rand(0, (strlen($str) - $len)), $len));
}
$code = array_unique($code); //移除數組中重複的值
$set_code = Array();
for ($j = 0; $j < $num; $j++) {
$set_code[] = $code[$j];
}
return $set_code;
}
小弟剛開始學習,希望能講的淺顯易懂些。
------解決方案--------------------
str_shuffle 的作用是將字串打亂,操作是以位元組為單位的
打亂後,原來相鄰的位元組,可能就不相鄰了
一個漢字需要靠相鄰的位元組來表示,所需位元組數依編碼定(gbk 2位元組、utf-8 3位元組、等等)
原來相鄰的變成不相鄰的了,就出現了“亂碼”
------解決方案--------------------
將substr()換成:subCNchar()試試,估計過不了str_shuffle(),建議自己寫個重組字串規則,如隨機抽取、加減乘除運算等等;
PHP code
/** 截取漢字 * * $str 要截取的字串 * $start 截取的起始位置 * $length 要截取的長度 * $charset 字串編碼 **/ function subCNchar($str, $start = 0, $length, $charset = "utf-8") { if (strlen($str) <= $length) return $str; $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/"; $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/"; $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/"; $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/"; preg_match_all($re[$charset], $str, $match); $slice = join("", array_slice($match[0], $start, $length)); return $slice; }
------解決方案--------------------
函數前面添加:
mb_internal_encoding('GBK');
當然不一定是GBK,根據你php檔案的字元集修改。
再就是產生圖片時你載入的字型必須支援中文。
------解決方案--------------------
頁面最頂加入header('Content-type: text/html;charset=UTF-8');