php - 删除无效/不完整的多字节字符

标签 php utf-8 iconv

我在对用户输入使用以下代码时遇到了一些问题:

htmlentities($string, ENT_COMPAT, 'UTF-8');

当检测到无效的多字节字符时,PHP 会抛出一个通知:

PHP Warning: htmlentities(): Invalid multibyte sequence in argument in /path/to/file.php on line 123

我的第一个想法是抑制错误,但这是缓慢且糟糕的做法: http://derickrethans.nl/five-reasons-why-the-shutop-operator-should-be-avoided.html

我的第二个想法是使用 ENT_IGNORE 标志,但即使是 PHP 手册也建议不要使用它:

Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » may have security implications.

一些更进一步的原因让我想到了以下代码:

    // detect encoding
$encoding =  mb_detect_encoding($query);
if($encoding != 'UTF-8') {
    $query = mb_convert_encoding($query, 'UTF-8', $encoding);
} else {
    // strip out invalid utf8 sequences
    $query = iconv('UTF-8', 'UTF-8//IGNORE', $query);
}

不幸的是,iconv 在删除/忽略无效字符时抛出 E_NOTICE:

If you append the string //TRANSLIT to out_charset transliteration is activated. This means that when a character can't be represented in the target charset, it can be approximated through one or several similarly looking characters. If you append the string //IGNORE, characters that cannot be represented in the target charset are silently discarded. Otherwise, str is cut from the first illegal character and an E_NOTICE is generated.

所以我在这里基本上没有选择。我宁愿使用久经考验的库来处理此类问题,也不愿尝试使用我见过的一些基于正则表达式的解决方案。

所以这引出了我的最后一个问题: 如何高效、安全地删除无效的多字节字符,而不会发出通知/警告/错误?

最佳答案

iconv('UTF-8', "ISO-8859-1//忽略", $string);

对我来说效果非常好。似乎没有产生任何通知。

关于php - 删除无效/不完整的多字节字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9631299/

相关文章:

php - 我总是需要使用 mysql_fetch

c++ - MSVC14 根据源是 UTF-8 还是 UTF-8 BOM 对 u8 前缀进行不同的处理

php - MySQL 数据库存储问号而不是特殊字符

Java解析UTF8

utf-8 - ColdFusion:将带重音的区域字符转换为纯ASCII

encoding - 不支持将编码从未知 8 位转换为 us-ascii

php - 为循环中的每个表行赋予唯一类

php - 如何从 DOMDocument 输出中过滤 <body> 内容?

php - 代码点火器/PHP : Image db storage?

php - iconv UTF-8//忽略仍然产生 "illegal character"错误