Home  >  Article  >  Backend Development  >  PHP 汉字截取字符串出现了问题!!大神快来啊!!!!!

PHP 汉字截取字符串出现了问题!!大神快来啊!!!!!

WBOY
WBOYOriginal
2016-06-06 20:41:12947browse

<code><br>$a='王多多';



echo mb_substr($a,0,2);

exit;


?>


</code>

按理说应该出现王多两个字,为什么出现了
我擦。。大神,这是为啥呢??????

回复内容:

<code><br>$a='王多多';



echo mb_substr($a,0,2);

exit;


?>


</code>

按理说应该出现王多两个字,为什么出现了
我擦。。大神,这是为啥呢??????

mb_substr指定编码即可解决。在线运行结果:http://3v4l.org/OsNXf

应该是PHP版本BUG吧,我看 对于没有指定编码的字符串,mb_substr是使用PHP默认编码进行处理的,对比各个版本的默认编码你会发现5.6以下都是ISO-8859-1,而只有5.6以上才是UTF-8(感谢 @kankana 的纠正)。 所以在5.6以上是没有问题的,可查看在线运行结果:http://3v4l.org/dFDgs

<code>mb_substr($a,0,2,'utf8')
</code>

根据:http://php.net/manual/zh/function.mb-substr.php

因为一个汉字占3个字节?
假如截取2的话,只是截取两个字符(一个字符一个字节)。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn