There are many methods to detect String Encoding. for example, you can use ord to obtain the character base and then enter the judgment, or use the mb_detect_encoding function to process it. The following describes several methods. example 1: The code is as follows: * nbs... there are many methods to detect String Encoding. for example, you can use ord to obtain the character base and then enter the judgment, or use the mb_detect_encoding function to process it. The following describes several methods.
Example 1,The code is as follows:
/*** Check whether the string is UTF8 encoded * @ param string $ str the detected string * @ 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 ;}
Example 2The code is as follows:
function is_utf8($string) { return preg_match('%^(?: [\x09\x0A\x0D\x20-\x7E] # ASCII | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3 | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15 | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16 )*$%xs', $string);
The accuracy is basically the same as that of mb_detect_encoding (). If you want to get the correct code together with the wrong one, the encoding detection cannot be 100% accurate. this can basically meet the requirements.
Example 3The code is as follows:
Function mb_is_utf8 ($ string) {return mb_detect_encoding ($ string, 'utf-8') === 'utf-8'; // New discoveries}
Example 4,The code is as follows:
// 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
Tutorial link:
Reprint at will ~ However, please keep the tutorial address★