gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 12:36:30 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com