PHP判斷字串編碼是否為utf-8的程式碼

來源:互聯網
上載者:User

我們以前常用mb_detect_encoding()此函數檢測字元編碼

 

 代碼如下 複製代碼
//判斷字串是什麼編碼
if ($tag === mb_convert_encoding(mb_convert_encoding($tag, "GB2312", "UTF-8"), "UTF-8", "GB2312")) {
}
else {//如果是gb2312 的就轉換為utf8的
$tag = mb_convert_encoding($tag, 'UTF-8', 'GB2312');
}

 $keytitle = “%D0%BE%C6%AC”;時。檢測結果卻是UTF-8.這個bug其實不算是bug,寫程式時也不應當過於依賴mb_detect_encoding,當字串較短時,檢測結果產生偏差的可能性很大。
怎麼解決呢,我的辦法是:

 代碼如下 複製代碼

$encode = mb_detect_encoding($keytitle, array('ASCII','GB2312′,'GBK','UTF-8');

個參數分別是:被檢測的輸入變數、編碼方式的檢測順序(一旦為真,後面自動忽略)、strict模式
對編碼檢測的順序進行調整,將最大可能性放在前面,這樣減少被錯誤轉換的機會。

上面辦法還是解決不了,下面又找到了一個解決方案。

例1

 代碼如下 複製代碼

// Returns true if $string is valid UTF-8 and false otherwise.
function is_utf8($word)
{
if (preg_match("/^([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){1}$/",$word) == true || preg_match("/([".chr(228)."-".chr(233)."]{1}[".chr(128)."-".chr(191)."]{1}[".chr(128)."-".chr(191)."]{1}){2,}/",$word) == true)
{
return true;
}
else
{
return false;
}
} // function is_utf8

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.