以下是如何使用 grapheme_extract() 逐字符循环遍历 UTF-8 字符串。
<?php
$str = "سabcक’…";
// 如果上一行没有出现,则字符串包含:
//U+0633,U+0061,U+0062,U+0063,U+0915,U+2019,U+2026
$n = 0;
for ( $start = 0, $next = 0, $maxbytes = strlen($str), $c = '';
$start < $maxbytes;
$c = grapheme_extract($str, 1, GRAPHEME_EXTR_MAXCHARS , ($start = $next), $next)
)
{
if (empty($c))
continue;
echo "This utf8 character is " . strlen($c) . " bytes long and its first byte is " . ord($c[0]) . "\n";
$n++;
}
echo "$n UTF-8 characters in a string of $maxbytes bytes!\n";
// 应该打印:字符串中包含 7 个 UTF-8 字符,共 14 个字节!
?>