php使用mb_check_encoding檢查字串在指定的編碼裡是否有效_PHP教程

來源:互聯網
上載者:User
mb_check_encoding — 檢查字串在指定的編碼裡是否有效
PHP 版本要求: (PHP 4 >= 4.4.3, PHP 5 >= 5.1.3)
說明:bool mb_check_encoding ([ string $var = NULL [, string $encoding = mb_internal_encoding() ]] )
檢查指定的位元組流在指定的編碼裡是否有效。它能有效避免所謂的“無效編碼攻擊(Invalid Encoding Attack)”。
參數
var
要檢查的位元組流。如果省略了這個參數,此函數會檢查所有來自最初請求所有的輸入。
encoding
期望的編碼。
傳回值
成功時返回 TRUE, 或者在失敗時返回 FALSE。
為了檢查是否一個字串編碼正確在utf - 8中,我建議以下函數實現 mb_check_encoding():
複製代碼 代碼如下:
function check_utf8($str) {
$len = strlen($str);
for($i = 0; $i < $len; $i++){
$c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) return false;
elseif ($c > 239) $bytes = 4;
elseif ($c > 223) $bytes = 3;
elseif ($c > 191) $bytes = 2;
else return false;
if (($i + $bytes) > $len) return false;
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) return false;
$bytes--;
}
}
}
return true;
} // end of check_utf8
?>

http://www.bkjia.com/PHPjc/825083.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/825083.htmlTechArticlemb_check_encoding — 檢查字串在指定的編碼裡是否有效 PHP 版本要求: (PHP 4 = 4.4.3, PHP 5 = 5.1.3) 說明:bool mb_check_encoding ([ string $var = NULL [, st...

  • 聯繫我們

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