← All writing

Count visible text deliberately: bytes are not characters

PHP 8.3+Sources checked 2026-09-13

A name limit that works with ASCII behaves strangely for Nepali text. strlen reports bytes, so a short Unicode name can use more bytes than its visible character count suggests. The correct measure depends on why the limit exists.

Distinguish storage from text length

<?php
$text = 'é';
assert(strlen($text) === 2);
if (extension_loaded('mbstring')) {
    assert(mb_strlen($text, 'UTF-8') === 1);
}

This example uses a single precomposed character. A visually identical character can also be represented using a base letter plus a combining accent. mb_strlen counts code points, not necessarily the clusters a person sees as one character. Grapheme-aware functions from the intl extension are useful when the product requirement is a visible-character limit.

Pick the rule for the boundary

A byte limit may be correct for an external protocol or a database constraint. A user-facing label limit often needs a text-aware measure. Keep both requirements if necessary: a friendly character limit and a separate storage or transport maximum.

Check the extensions available on the actual hosting runtime. The browser PHP version and the cron PHP version may load different extension sets. Do not discover missing mbstring only after receiving your first non-ASCII customer name.

Test ASCII, Nepali script, combining accents, and emoji sequences. Avoid slicing text at arbitrary byte positions because that can produce invalid UTF-8. If truncation is required, choose the matching multibyte or grapheme operation and preserve the original value elsewhere when the business needs it.

Reference

Official documentation. The examples here illustrate the stated boundary; adapt them to your application and test its failure paths.