php函数substr、strlen计算中文字节数不准确的问题

PHP与SEO 思享 786浏览

使用场景:post提交数据,对数据的字节长度有限制,为了避免字符串过长而导致post失败,需要使用strlen函数获取字符串字节数,然后通过判断,使用substr截取字符串确保长度在限制内。然而在使用过程中,发现依旧存在post失败的情况

问题原因

因为编码问题,strlen获取的字符串字节数会存在差异,因此导致strlen没超过的字符串,post却返回字节过长。

如下摘自网络文章

关于中文的问题,PHP内置的字符串长度函数strlen无法正确处理中文字符串,它得到的只是字符串所占的字节数。对于GB2312的中文编码,strlen得到的值是汉字个数的2倍,而对于UTF-8编码的中文,就是3倍的差异了(在UTF-8编码下,一个汉字占3个字节)。

问题解决

mb_strlen() 函数可以指定字符编码,用此函数替代获取字符串字节数函数strlen()

同理,使用mb_substr() 函数代替substr() 进行字符串截取

注意:如mb_strlen() 报错需设置php.ini开启

推荐阅读

Function get_magic_quotes_gpc() is deprecated报错解决办法

在 PHP 7.4 及更高版本中, get_magic_quotes_gpc() 函数已被弃用。 This means that code using this function will raise a warning or error.以下是解决......

PHP提示:Warning: count():Parameter must be an array or an object that implements Countable

错误原因:PHP7.2以后,count()函数的参数无效时会抛出warning警告。...

PHP7.4 报错:Deprecated Functionality: implode(): Passing glue string after array is deprecated.

PHP7.4运行项目报错:Deprecated Functionality: implode(): Passing glue string after array is deprecated。只需交换 implode() 函数的两个参数!...