Backend Development 2 min read

PHP mb_strlen() – Get String Length

The mb_strlen() function in PHP returns the number of characters in a string, correctly handling multibyte characters and allowing an optional encoding parameter, with examples showing differences from strlen() under various encodings.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
PHP mb_strlen() – Get String Length

The mb_strlen() function retrieves the length of a string, counting each multibyte character as a single unit. It accepts two parameters: $str (the string to measure) and an optional $encoding (character encoding). If $encoding is omitted, the internal character encoding is used.

Return value: the number of characters in $str according to the specified encoding; returns FALSE if the provided encoding is invalid.

Example usage demonstrates the difference between strlen() and mb_strlen() with UTF‑8, GBK, and GB2312 encodings:

<?php
    // Ensure the source file is saved as UTF‑8
    $str = '中文a字1符';
    echo strlen($str)."<br>"; // outputs 14
    echo mb_strlen($str, 'utf8')."<br>"; // outputs 6
    echo mb_strlen($str, 'gbk')."<br>";   // outputs 8
    echo mb_strlen($str, 'gb2312')."<br>"; // outputs 10
?>
encodingmb_strlenMultibytestring length
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.