我正在使用 substr 方法访问字符串的前 20 个字符。它在正常情况下工作正常,但在使用 rtl 语言 (utf8) 时它给了我错误的结果(显示了大约 10 个字符)。我在网上搜索过,但发现第 nth 对解决这个问题很有用。这是我的代码行:
substr($article['CBody'],0,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'], 0, 20, 'UTF-8');
echo utf8_decode($str);
希望这对您有所帮助。
关于php - substr 不适用于 utf8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14785682/