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

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

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.

所以我基本上没有选择.我宁愿使用经过试验和测试的库来处理这种东西,而不是尝试使用我见过的一些基于正则表达式的解决方案.

所以这引出了我的最后一个问题:

如何在没有通知/警告/错误的情况下有效,安全地删除无效的多字节字符?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值