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
+5.5k Golang : Embedded or data bundling example
+4.2k Golang : Get FX sentiment from website example
+12.1k Golang : How to get a user home directory path?
+4.1k Golang : Display packages names during compilation
+8.2k Mac OSX : Get a process/daemon status information
+7.2k Golang : Check if integer is power of four example
+10.3k Golang : How to flush a channel before the end of program?
+13.3k Golang : Convert(cast) int to float example
+9.9k Golang : How to determine a prime number?
+32.8k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+9.6k Golang : Get currencies exchange rates example
+24.6k Golang : missing Mercurial command