以下是如何使用 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 "這個 utf8 字元長度為 " . strlen($c) . " 位元組,其第一個位元組為 " . ord($c[0]) . "\n";
$n++;
}
echo "$n 個 UTF-8 字元在一個 $maxbytes 位元組的字串中!\n";
// 應該印出:7 個 UTF8 字元在一個 14 位元組的字串中!
?>