php删除非utf8字符的方法:首先创建一个php示例文件;然后使用正则表达式“preg_replace($regex, '$1', $text);”方法删除非utf8字符即可。
本文操作环境:windows7系统、php7.1版,dell g3电脑
具体问题:
php怎么删除非utf8字符?
php 从字符串中删除非utf8字符
我在从字符串中删除非utf8字符时出现问题,这些字符无法正确显示。像这样的字符0x97 0x61 0x6c 0x6f(十六进制表示)
删除它们的最佳方法是什么?正则表达式还是其他?
解决办法:
使用正则表达式方法:
$regex = <<<'end'/ ( (?: [\x00-\x7f] # single-byte sequences 0xxxxxxx | [\xc0-\xdf][\x80-\xbf] # double-byte sequences 110xxxxx 10xxxxxx | [\xe0-\xef][\x80-\xbf]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2 | [\xf0-\xf7][\x80-\xbf]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3 ){1,100} # ...one or more times )| . # anything else/xend;preg_replace($regex, '$1', $text);
它搜索utf-8序列,并将其捕获到组1中。它还匹配无法识别为utf-8序列的一部分的单个字节,但不捕获这些字节。替换是捕获到组1中的任何内容。这将有效删除所有无效字节。
通过将无效字节编码为utf-8字符,可以修复字符串。但是,如果错误是随机的,则可能会留下一些奇怪的符号。
$regex = <<<'end'/ ( (?: [\x00-\x7f] # single-byte sequences 0xxxxxxx | [\xc0-\xdf][\x80-\xbf] # double-byte sequences 110xxxxx 10xxxxxx | [\xe0-\xef][\x80-\xbf]{2} # triple-byte sequences 1110xxxx 10xxxxxx * 2 | [\xf0-\xf7][\x80-\xbf]{3} # quadruple-byte sequence 11110xxx 10xxxxxx * 3 ){1,100} # ...one or more times )| ( [\x80-\xbf] ) # invalid byte in range 10000000 - 10111111| ( [\xc0-\xff] ) # invalid byte in range 11000000 - 11111111/xend;function utf8replacer($captures) { if ($captures[1] != "") { // valid byte sequence. return unmodified. return $captures[1]; } elseif ($captures[2] != "") { // invalid byte of the form 10xxxxxx. // encode as 11000010 10xxxxxx. return "\xc2".$captures[2]; } else { // invalid byte of the form 11xxxxxx. // encode as 11000011 10xxxxxx. return "\xc3".chr(ord($captures[3])-64); }}preg_replace_callback($regex, "utf8replacer", $text);
编辑:
!empty(x)将匹配非空值(0被认为是空的)。
x != 将匹配非空值,包括0。
x !== 将匹配以外的任何内容。
在这种情况下,x != 似乎是最好的选择。
我也加快了比赛速度。而不是单独匹配每个字符,它匹配有效的utf-8字符序列。
推荐学习:《php视频教程》
以上就是php怎么删除非utf8字符的详细内容。