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.
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
?>Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.