PHP:是否可以正确地对 UTF-8 字符串进行 SUBSTR?

标签 php encoding utf-8 substring

我有(在 SQLite 数据库中)以下字符串:

Лампа в вытяжке на кухне меняется, начиная с вытаскивания белого штырька справа。

PHP 使用 print 正确显示了该字符串。我只想获取该字符串的前 50 个字符,即

Лампа вытяжке на кухне меняется, начиная с вытас.

我尝试过同时使用substr 和 mb_substr,得到

Лампа в вытяжке на кухне ме�,即只有 28 个字符。

在阅读了这里和其他地方关于 mbstring 的问题之后,我意识到这实际上是一个 50 字节的字符串(22 个俄语字符 = 44 个字节加 5 个空格加 1 个问号)。

有什么好的解决办法吗?我所有的字符串都是 UTF-8,所以我当然可以自己编写一个 substr 函数,通过检查每个字节的第一位等。但这肯定已经完成了,对吧?

更新:我相信 mb_substr 不能正常工作,因为 mb_detect_encoding() does not work properly .

最佳答案

见以下网址:

在 PHP 中从 UTF-8 字符串中提取子字符串

http://osc.co.cr/extracting-a-substring-from-a-utf-8-string-in-php/

带有 UTF-8 的 PHP 子串

http://greekgeekz.blogspot.in/2010/11/php-substring-with-utf-8.html

或者试试看:

示例#1

$str1 = utf8_encode("Feliz día");

$str2 = substr($str1, 0, 9);

echo utf8_decode($str2); 

// will output Feliz d�

示例#2

$str3 = mb_substr($str1, 0, 9, 'UTF-8');

echo utf8_decode($str3); 

// will output Feliz dí

从 PHP >= 5.3 开始,您还可以声明编码指令并使用 substr 函数

示例 #3

declare(encoding='UTF-8');

$str4 = "Feliz día";

$str5 = substr($str4, 0, 9);echo $str5;


// will output Feliz dí

关于PHP:是否可以正确地对 UTF-8 字符串进行 SUBSTR?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12446877/

相关文章:

javascript - 显示 ajax 结果数据保存

php - 如果 MySQL 中的数据为 NULL,则将其替换为 PHP

php - 使用 Artisan 调用 php artisan migrate

ruby-on-rails - 如何防止错误 "code converter not found (UTF-8)"?

encoding - 如何使用UTF-8编码的SQLite ODBC驱动程序?

ios - 无法在 iOS 中将\\u00e2\\u0080\\u0099 解码为 ’

PHP UTF-8 不工作

php - 如何在magento核心资源中设置utf8字符集?

Python:Beautifulsoup 为 tis-620、字符集 windows-874 返回错误的解码

javascript - 如果单击按钮后输入字段为空,则不应提交