我使用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);
希望这可以帮助.