php - 使用 UTF-8 和 mb_substr 的损坏数据

标签 php utf-8 mbstring

我从 MySQL 数据库 varchar(255) utf8_general_ci 字段获取数据,并尝试使用 PHP 将文本写入 PDF。我需要确定 PDF 中的字符串长度以限制表格中文本的输出。但是我注意到 mb_substr/substr 的输出真的很奇怪。

例如:

mb_internal_encoding("UTF-8");

$_tmpStr = $vfrow['title'];
$_tmpStrLen = mb_strlen($vfrow['title']);
for($i=$_tmpStrLen; $i >= 0; $i--){
     file_put_contents('cutoffattributes.txt',$vfrow['field']." ".$_tmpStr."\n",FILE_APPEND);
     file_put_contents('cutoffattributes.txt',$vfrow['field']." ".mb_substr($_tmpStr, 0, $i)."\n",FILE_APPEND);
}

输出这个:

screen shot from npp

npp file link

数据库:

enter image description here enter image description here

我的问题是多余的字符是从哪里来的?

最佳答案

  1. 您需要通过适本地设置连接编码来确保您实际上是以 UTF-8 编码从数据库中获取数据。这取决于您的数据库适配器,请参阅 UTF-8 all the way through了解详情。
  2. 您需要告诉您的 mb_ 函数数据是 UTF-8 格式,以便它们可以正确处理它。使用 mb_internal_encoding 为所有函数全局设置此项,或者在调用函数时将 $encoding 参数传递给函数:

    mb_substr($_tmpStr, 0, $i, 'UTF-8')
    

关于php - 使用 UTF-8 和 mb_substr 的损坏数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29803193/

相关文章:

php - 将 mbstring 添加到 laravel 5 应用程序的 docker 图像

installation - 在 Mac 上安装 phpMyAdmin 时缺少 mbstring PHP 扩展

PHP/MySQL 编码

php - 从 mysql 表中选择随机行

c++ - 通过检查输入字节确定输入编码

php - 如何从字符串中删除 'em' 破折号?

c# - 如何在 C# 中将 "=?utf-8?B?...?="解码为字符串

java - 从 Android 上传图像时,Ruby 服务器上出现 argumenterror in utf-8 错误字节序列

php - 使用 CodeIgniter 插入语句——太困惑了

php - 来自 PHP 的 XMLHttpRequestProgressEvent 操作