PHP中strlen函数统计字符异常求助:预期输出11实际得23
strlen() Output in PHP Hey there! Let's figure out why your strlen() call is returning 23 instead of the expected 11 for the string "Subdivision".
The Root Cause
First, a quick reminder: PHP's strlen() counts bytes, not characters. For standard ASCII English text like "Subdivision", each character takes up 1 byte—so a length of 11 makes perfect sense. A result of 23 means your string is hiding extra, invisible bytes. These are usually things like zero-width spaces, non-printable control characters, or leftover formatting gunk from copying/pasting from rich text sources (like Word docs or formatted web pages).
Steps to Diagnose the Hidden Bytes
Let's expose those sneaky extra bytes using bin2hex() to see the raw hex representation of your string:
$string = "Subdivision"; echo bin2hex($string);
For a clean "Subdivision", you should see this output:5375626469766973696f6e
If your output is twice as long (or longer), that confirms extra bytes are mixed in—for example, zero-width spaces show up as e2808b in UTF-8.
Fix the Issue
To strip out all non-alphabetic characters (including the hidden ones), use a regular expression to clean your string:
$string = "Subdivision"; // Keep only uppercase and lowercase English letters $cleanedString = preg_replace('/[^a-zA-Z]/', '', $string); echo strlen($cleanedString); // This should now output 11
If you need to preserve other valid characters (like spaces or punctuation), adjust the regex to include them—for example, /[^a-zA-Z\s]/ would keep spaces alongside letters.
Bonus Tip for UTF-8 Text
While this isn't the issue here, if you regularly work with multi-byte languages or UTF-8 text, swap strlen() for mb_strlen() to count actual characters (not bytes):
echo mb_strlen($string, 'UTF-8');
内容的提问来源于stack exchange,提问作者sushil vishwakarma

