微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – substr与utf8不兼容

我使用substr方法来访问字符串的前20个字符.它在正常情况下工作正常,但在使用rtl语言(utf8)时,它会给我错误的结果(显示大约10个字符).我在网上搜索过,但发现第n个问题很有用.这是我的代码行:

substr($article['CBody'],20);

提前致谢.

最佳答案

If you’re working with strings encoded as UTF-8 you may lose
characters when you try to get a part of them using the PHP substr
function. This happens because in UTF-8 characters are not restricted
to one byte,they have variable length to match Unicode characters,
between 1 and 4 bytes.

您可以使用mb_substr(),它的工作方式与substr几乎相同,但区别在于您可以添加新参数来指定编码类型,无论是UTF-8还是不同的编码.

试试这个:

$str = mb_substr($article['CBody'],20,'UTF-8');

echo utf8_decode($str); 

希望这可以帮助.

原文地址:https://www.jb51.cc/mysql/433444.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐