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
+11.2k Golang : convert(cast) string to integer value
+4.6k Unix/Linux : How to find out the hard disk size?
+3.4k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+5.2k Javascript : Get operating system and browser information
+8.2k Golang : Generate Codabar
+3.8k JavaScript: Add marker function on Google Map
+8.7k Golang : Populate slice with sequential integers example
+5.6k Golang : Embedded or data bundling example
+18.8k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+25.2k Golang : Encrypt and decrypt data with AES crypto
+8.6k Golang : interface - when and where to use examples
+4.3k Golang : Get FX sentiment from website example