PHP中檢測檔案是否為UTF-8編碼的函數

來源:互聯網
上載者:User
// // 測試文本是否是utf8編碼// // 返回值://   1 - 有BOM頭的內容//   2 - 純utf8的內容//   3 - 較可能是utf8的內容//   4 - 較不可能是utf8的內容// function utf8_check($text){  $utf8_bom = chr(0xEF).chr(0xBB).chr(0xBF);    // BOM頭檢查  if (strstr($text, $utf8_bom) === 0)    return 1;    $text_len = strlen($text);    // UTF-8是一種變長位元組編碼方式。對於某一個字元的UTF-8編碼,如果只有一個位元組則其最高二進位位為0;  // 如果是多位元組,其第一個位元組從最高位開始,連續的二進位位值為1的個數決定了其編碼的位元,其餘各位元組均以10開頭。  // UTF-8最多可用到6個位元組。  //  // 如表:  // < 0x80 1位元組 0xxxxxxx  // < 0xE0 2位元組 110xxxxx 10xxxxxx  // < 0xF0 3位元組 1110xxxx 10xxxxxx 10xxxxxx  // < 0xF8 4位元組 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx  // < 0xFC 5位元組 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx  // < 0xFE 6位元組 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx    $bad   = 0; // 不符合utf8規範的字元數  $good  = 0; // 符號utf8規範的字元數    $need_check = 0; // 遇到多位元組的utf8字元後,需要檢查的連續位元組數  $have_check = 0; // 已經檢查過的連續位元組數    for ($i = 0; $i < $text_len; $i ++) {    $c = ord($text[$i]);    if ($need_check > 0) {      $c = ord($text[$i]);      $c = ($c >> 6) << 6;            $have_check ++;            // 10xxxxxx ~ 10111111      if ($c != 0x80) {        $i -= $have_check;        $need_check = 0;        $have_check = 0;        $bad ++;      }      else if ($need_check == $have_check) {        $need_check = 0;        $have_check = 0;        $good ++;      }            continue;    }        if ($c < 0x80)      // 0xxxxxxx      $good ++;    else if ($c < 0xE0) // 110xxxxx      $need_check = 1;    else if ($c < 0xF0) // 1110xxxx      $need_check = 2;    else if ($c < 0xF8) // 11110xxx      $need_check = 3;    else if ($c < 0xFC) // 111110xx      $need_check = 4;    else if ($c < 0xFE) // 1111110x      $need_check = 5;    else      $bad ++;  }    if ($bad == 0)    return 2;  else if ($good > $bad)    return 3;  else    return 4;}

以上就介紹了 PHP中檢測檔案是否為UTF-8編碼的函數,包括了方面的內容,希望對PHP教程有興趣的朋友有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.