The content of this article is about how PHP filters out characters that are not UTF8 (code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
function utf8_filter($data) { $str = ""; for($n = 0; $n < strlen($data);) { $s = substr($data, $n, 1); $v = ord($s); if($v >= 127) { ++$n; $cnt = 0; $tmp = $v; while($tmp & 0x80) { $tmp = $tmp << 1; ++$cnt; } $x = 0; while($x < $cnt && $n < strlen($data)) { $s = substr($data, $n, 1); if((ord($s) & 0xC0) == 0x80) { ++$n; ++$x; }else{ break; } } if($x + 1 == $cnt) { $str = $str . substr($data, $n - $cnt, $cnt); }else{ while($n < strlen($data)) { $s = substr($data, $n, 1); if(ord($s) & 0x80) { ++$n; }else{ break; } } } }else{ $str = $str. $s; ++$n; } } return $str; }
Related recommendations:
Filter characters that exceed three bytes in utf8 characters, or non-utf8 characters
PHP implements filtering out non-Chinese characters and retaining only Chinese characters,
The above is the detailed content of How to filter out characters that are not UTF8 in PHP (code). For more information, please follow other related articles on the PHP Chinese website!