本文介绍了如何在PHP中迭代UTF-8字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用索引逐个字符地迭代UTF-8字符串?
How to iterate a UTF-8 string character by character using indexing?
使用方括号运算符$str[0]
访问UTF-8字符串时,utf编码的字符包含2个或更多元素.
When you access a UTF-8 string with the bracket operator $str[0]
the utf-encoded character consists of 2 or more elements.
例如:
$str = "Kąt";
$str[0] = "K";
$str[1] = "�";
$str[2] = "�";
$str[3] = "t";
但我希望拥有:
$str[0] = "K";
$str[1] = "ą";
$str[2] = "t";
可以使用mb_substr
,但这非常慢,即.
It is possible with mb_substr
but this is extremely slow, ie.
mb_substr($str, 0, 1) = "K"
mb_substr($str, 1, 1) = "ą"
mb_substr($str, 2, 1) = "t"
是否有另一种方法可以在不使用mb_substr
的情况下逐字符插入字符串?
Is there another way to interate the string character by character without using mb_substr
?
推荐答案
使用 preg_split .使用"u"修饰符,它支持UTF-8 Unicode
Use preg_split. With "u" modifier it supports UTF-8 unicode.
$chrArray = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
这篇关于如何在PHP中迭代UTF-8字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!