php - substr 不适用于 utf8

标签 php mysql utf-8 right-to-left substr

我正在使用 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/

相关文章:

c++ - 使用 libcurl 下载 UTF-8 文件(ANSI 工作正常)

php - 不将 Bootstrap 日期值保存到 Laravel 中的数据库表中

MySQL 手动更改跟踪

java - 间歇性连接错误 - 连接超时 - mysql jboss java

mysql - 通过 grails 应用程序中的网络表单提交特殊字符,例如 "š č ć đ ž"

google-chrome - Chrome 扩展程序存在有关 UTF-8 的 content.js 错误

php - laravel 5 查询急切加载的多重约束

php - Bootstrap Select 插件 - 如何使用它提交表单?

php - 在 solr/lucene 中过滤存储在远程数据库中的字段的最佳方法?

php - 用于从对话和消息表连接中选择最新消息的 MySql 查询