iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐙

PHP: Calculating the Length of Strings with Extended Grapheme Clusters Using Regex

に公開

I was curious about the performance difference when using regular expressions (PCRE, Oniguruma) as an alternative to grapheme_strlen from the intl module in environments where it is unavailable, so I decided to measure it.

I will check whether grapheme_strlen, preg_match_all, and mbstring functions can correctly count the following Kanji characters. Note that U+E0100 is a variation selector.

$str = "竈門禰\u{E0100}豆子";

var_dump(
    5 === grapheme_strlen($str),
    5 === grapheme_count($str),
    5 === grapheme_count2($str)
);
function grapheme_count(string $str): int
{
    return preg_match_all('/\X/su', $str);
}

function grapheme_count2(string $str): int
{
    mb_ereg_search_init($str, '\X');
    $length = 0;

    while (mb_ereg_search()) {
        ++$length;
    }

    return $length;
}

The execution results are as follows:

> php test.php
bool(true)
bool(true)
bool(true)

Next, let's measure the performance.

$str = "竈門禰\u{E0100}豆子";

$timer = timer([
    'grapheme_strlen' => function() use($str) { grapheme_strlen($str); },
    'preg_match_all' => function() use($str) { grapheme_count($str); },
    'mb_ereg_search' => function() use($str) { grapheme_count2($str); }
]);

foreach ($timer as $message => $time) {
    echo $message, PHP_EOL, $time, PHP_EOL;
}
function timer(array $callables, int $repeat = 100000): array
{
    $ret = [];
    $save = $repeat;
    
    foreach ($callables as $key => $callable) {
        $start = hrtime(true);

        do {      
            $callable();
        } while($repeat -= 1);

        $stop = hrtime(true);
        $ret[$key] = $stop - $start;
        $repeat = $save;
    }

    return $ret;
}

The measurement results are as follows:

> php test.php
grapheme_strlen
94997600
preg_match_all
34618900
mb_ereg_search
324994600

Discussion