PHP : Proper way to get UTF-8 character or string length
Problem :
Was trying to get a length of an unicode(UTF-8) character with PHP. Trouble is, PHP echoes back 3, which is technically correct, but not accurate.
For example :
<?php
echo strlen('黄');
?>
will return 3 instead of 1. How to get PHP to count the unicode character as 1?
Diagnostic :
UTF-8 character is multi-byte and need to tell PHP to use the proper encoding to measure the length.
Solution :
Use mb_strlen()
function with UTF-8
encoding to get the string length. For example :
<?php
echo mb_strlen('黄', 'UTF-8');
?>
Output :
1
which is accurate.
References :
See also : PHP : Extract part of a string starting from the middle
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.1k Golang : concatenate(combine) strings
+4.9k Golang : Error handling methods
+9.7k Golang : Simple File Server
+29k Golang : How to verify uploaded file is image or allowed file types
+12.5k Golang : Read from buffered reader until specific number of bytes
+32.6k Golang : All update packages with go get command
+3.8k Linux/MacOSX : Search and delete files by extension
+13.2k Golang : Google Drive API upload and rename example
+9.4k Golang : How to get quoted string into another string?
+49.5k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+12.5k Golang : reCAPTCHA example
+5k Cash Flow : 50 days to pay your credit card debt