gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:11:58 26 4
gpt4 key购买 nike

我有(在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com