PHP strlen() vs mb_strlen(): bytes, code points, and graphemes

strlen() counts bytes. mb_strlen($text, 'UTF-8') counts Unicode code points in valid UTF-8. The Korean sample 가나다 uses nine bytes for three code points. Use grapheme_strlen() when a group that looks like one character should count once.

Compare byte length and character count

Save the example as UTF-8 in length.php and run php length.php. The mbstring extension is required for mb_strlen(). The three inputs produce the lengths in the table. The space in the first string counts too.

<?php
if (!extension_loaded('mbstring')) {
    exit('Enable the mbstring extension.' . PHP_EOL);
}
foreach (['123 abc', '가나다', ''] as $text) {
    echo json_encode([
        'text' => $text,
        'bytes' => strlen($text),
        'characters' => mb_strlen($text, 'UTF-8'),
    ], JSON_UNESCAPED_UNICODE), PHP_EOL;
}
UTF-8 string strlen() mb_strlen(..., "UTF-8")
123 abc 7 7
가나다 9 3
Empty string 0 0

Use strlen() for a storage or transfer limit in bytes and mb_strlen() for a UTF-8 code-point limit. Check which unit the destination or input rule actually specifies. PHP Manual — strlen() PHP Manual — mb_strlen()

Distinguish choosing an encoding from converting it

The second argument of mb_strlen() selects how to interpret the existing bytes. To change those bytes to another encoding, use mb_convert_encoding(). Save the example as encoding-length.php and run php encoding-length.php.

<?php
if (!extension_loaded('mbstring')) {
    exit('Enable the mbstring extension.' . PHP_EOL);
}
$utf8 = '가나다';
$euckr = mb_convert_encoding($utf8, 'EUC-KR', 'UTF-8');
if ($euckr === false) {
    exit('The conversion failed.' . PHP_EOL);
}
echo strlen($utf8), PHP_EOL;
echo mb_strlen($utf8, 'UTF-8'), PHP_EOL;
echo strlen($euckr), PHP_EOL;
echo mb_strlen($euckr, 'EUC-KR'), PHP_EOL;

The result is 9, 3, 6, 3. After conversion, the sample uses six bytes in EUC-KR and still counts as three characters when read as EUC-KR. The sample is representable in both encodings. When converting other data, check for loss because EUC-KR cannot represent every Unicode character. PHP Manual — mb_convert_encoding()

Omit the encoding or pass null and PHP uses mbstring’s internal encoding. Inspect it with mb_internal_encoding(). The HTML meta charset does not set this argument. Pass the encoding explicitly when the input format is fixed. PHP Manual — mb_internal_encoding()

Count what looks like a single character

A code point is a Unicode value assigned to a character or combining mark. A base letter and an accent can form one grapheme cluster, a unit that looks like a single character. grapheme_strlen() counts these clusters in valid UTF-8. Save the example as graphemes.php and run php graphemes.php with mbstring and intl.

<?php
if (!extension_loaded('mbstring') || !extension_loaded('intl')) {
    exit('The mbstring and intl extensions are required.' . PHP_EOL);
}
foreach (["e\u{0301}", "\u{00E9}"] as $text) {
    $count = grapheme_strlen($text);
    if (!is_int($count)) {
        exit(1);
    }
    printf("%d, %d, %d\n",
        strlen($text),
        mb_strlen($text, 'UTF-8'),
        $count
    );
}

The decomposed sequence e + U+0301 has three bytes, two code points, and one grapheme cluster. Precomposed é has two bytes, one code point, and one cluster. For a visible-character limit use the last measure. Distinguish the false or null that grapheme_strlen() may return on failure from a length of zero. PHP Manual — grapheme_strlen()

Validate UTF-8 input and troubleshoot extensions

<?php
if (!extension_loaded('mbstring')) {
    exit('Enable the mbstring extension.' . PHP_EOL);
}
$name = '가나다';
if (!is_string($name)) {
    echo 'Input must be a string.', PHP_EOL;
} elseif (!mb_check_encoding($name, 'UTF-8')) {
    echo 'The input is not valid UTF-8.', PHP_EOL;
} elseif (mb_strlen($name, 'UTF-8') > 2) {
    echo 'Enter no more than two code points.', PHP_EOL;
} else {
    echo 'The input meets the length requirement.', PHP_EOL;
}

Save the final example as validate-length.php and run php validate-length.php. It checks for a string, verifies UTF-8, and then applies a maximum of two code points. 가나다 exceeds the limit. Change it to 가나 to see the success message. Use a separate check if the field is required or has rules for empty input. PHP Manual — mb_check_encoding()

If mb_strlen() is undefined, run php -m to see whether command-line PHP loads mbstring. For a web issue, check the runtime serving the request too. PHP 8 and later throw ValueError for unsupported encoding names, so use names from your application’s allowed list. PHP Manual — Installing mbstring