Detecting whether the string is encoded UTF8

/**
 * UTF8 encoded string is detected
 * @Param string $ str string to be detected
 * @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;
}

 

Guess you like

Origin www.cnblogs.com/bluealine/p/11040716.html