正则匹配异常的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
/x
END;
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
/x
END;
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字符序列。