检测字符串是否为UTF8编码

/**
 * 检测字符串是否为UTF8编码
 * @param  string  $str 被检测的字符串
 * @return boolean      
 */
function is_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;
}
原文地址:https://www.cnblogs.com/bluealine/p/11040716.html