strlen(): Length of the string

Measure string length

strlen() returns the number of bytes in a string. For UTF-8 text where you need character count, use mb_strlen() with the appropriate encoding.

$text = 'plus2net';
echo strlen($text); // 8 bytes

$utf8 = 'café';
if (function_exists('mb_strlen')) {
    echo mb_strlen($utf8, 'UTF-8'); // 4 characters
}
echo strlen('plus2net.com'); // Ouptut is 12
Output is the length of the string in bytes.
For form input validation, check whether input is present and validate the expected length. `strlen()` counts bytes, not user-visible Unicode characters.

PHP function strlen returns number of bytes inside the string including blank space. If you want blank space to be removed then you can apply string replace function str_replace to the string before applying strlen.
$string="This is my string";
echo "Length of the string = ".strlen($string);
The output is 17 bytes, including the three spaces.

Length of the string after removing blank spaces

We will use str_replace function to search and replace all occurrences of blank space.
$string="This is my string";
$string=str_replace(" ","",$string);
echo "Length of the string = ".strlen($string);
The output is 14 bytes, because removing three spaces from a 17-byte ASCII string gives 14.

Maximum and minimum length of string

For an ASCII-only user ID, validate the byte length against the required limits. For international text, use a Unicode-aware length check and explicit validation rules.

$userId = "abcdababcdababcs";
$length = strlen($userId);
if ($length >= 6 && $length <= 15) {
    echo "Length is within 6 to 15 bytes";
} else {
    echo "Length must be between 6 and 15 bytes";
}

Nullable inputs and strlen()

$value = null;
$text = $value ?? '';
echo strlen($text); // 0
echo strlen(''); // 0
Passing null directly to strlen() is deprecated in PHP 8.1+. Normalize nullable input to a string first (as shown above), then separately validate whether a required field was actually provided.

strlen() returns bytes, not Unicode characters. The mb_strlen() example requires the mbstring extension.
strrev(): PHP string reverse
String Functions strrev(): PHP string reverse nl2br() To add Line break


Subscribe to our YouTube Channel here



plus2net.com







elyn espanola

05-02-2012

what are the php codes of counting different letters from 2 words that given by the users and each word will be equal to the number of letters that are different to the other words. for example: cat=1 bratt=2 since in the word cat,there is no letter c in the other word so it equals to 1, then in the second word, there is no letter b and r in the first word so it equals to 2,tnx,,i need ur ideas.
dickson

07-12-2012

nice stuff. home 4 the best. tank




PHP video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer