A Common Method for PHP to Detect If a String Is UTF8 Encoded

  • 2021-08-05 09:29:40
  • OfStack

This paper summarizes the common methods for PHP to detect whether a string is encoded by UTF8. Share it for your reference. The specific implementation method is as follows:

There are many ways to detect string coding, such as using ord to obtain the binary of characters and then enter the judgment, or using mb_detect_encoding function to deal with it. The following four commonly used methods are sorted out for your reference.

Example 1

/**
* Detects whether the string is UTF8 Code
* @param string $str 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 2
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 rate is basically the same as that of mb_detect_encoding (), with one right and one wrong.
Coding detection can't be 100% accurate, and this thing can basically meet the requirements.
Example 3
function mb_is_utf8($string)   
{  
    return mb_detect_encoding($string, 'UTF-8') === 'UTF-8';// A new discovery   
}

Example 4

// 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

I hope this article is helpful to everyone's PHP programming.


Related articles: