我在用户输入上使用以下代码时遇到一些问题:
htmlentities($string, ENT_COMPAT, 'UTF-8');
当检测到无效的多字节字符时,PHP会发出通知:
PHP Warning: htmlentities(): Invalid multibyte sequence in argument in /path/to/file.php on line 123
我的第二个想法是使用ENT_IGNORE标志,但即使是PHP手册也建议不要使用它:
Silently discard invalid code unit sequences instead of returning an empty string. Using this flag is discouraged as it » 07001.
进一步的原因使我得到了以下代码:
// 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.
所以我基本上没有选择.我宁愿使用经过试验和测试的库来处理这种东西,而不是尝试使用我见过的一些基于正则表达式的解决方案.
所以这引出了我的最后一个问题:
如何在没有通知/警告/错误的情况下有效,安全地删除无效的多字节字符?