Mastering PHP’s strlen(): How to Accurately Measure String Length
This article explains PHP's strlen() function, its syntax, and provides clear code examples showing how to calculate string lengths—including handling spaces and encoding considerations—for practical use cases like input validation.
strlen() is a commonly used PHP string function that calculates the length of a string, including spaces and special characters but excluding the null character.
The syntax is: int strlen ( string $string ) $string represents the string whose length is to be calculated.
Example 1: Calculate string length
$str = "Hello, world!"; // define a string
echo strlen($str); // output string lengthThe output is:
13Example 2: Calculate length ignoring spaces
$str = " Hello, world! "; // string with spaces
echo strlen($str); // length with spaces
echo strlen(trim($str)); // length after trimming spacesThe output is:
23
13These examples show that strlen() is widely used for quickly counting string length, useful in scenarios such as limiting usernames on social sites or product name lengths in e‑commerce.
Note that strlen() only reliably handles UTF‑8 and ISO‑8859‑1 encoded strings; other encodings may produce incorrect results.
When using strlen(), be aware of special or Chinese characters, as their byte size varies with encoding and can affect the length calculation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.
