Codectionary / Developer documentation / PHP

PHP multibyte text lengths

With the mbstring extension enabled, mb_strlen counts characters in a specified encoding. strlen counts bytes. Neither is a universal count of visible grapheme clusters.

Syntax

mb_strlen($text, "UTF-8")

Examples

PHP multibyte text lengths

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$word = 'café';
echo strlen($word), PHP_EOL;
echo mb_strlen($word, 'UTF-8'), PHP_EOL;
  1. For this UTF-8 source file output is 5, then 4. The accented letter occupies two bytes but one Unicode code point.

Best practices

  • Pass the encoding explicitly and enable mbstring. For user-perceived character limits consider grapheme_strlen from the intl extension.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading