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
+17.3k Golang : Parse date string and convert to dd-mm-yyyy format
+20.9k Golang : Create and resolve(read) symbolic links
+6.2k PHP : Proper way to get UTF-8 character or string length
+13k Golang : Linear algebra and matrix calculation example
+9.8k Golang : Read file and convert content to string
+6.3k Golang : Convert an executable file into []byte example
+13.3k Golang : Query string with space symbol %20 in between
+9.7k Golang : Convert octal value to string to deal with leading zero problem
+8.9k Golang : Create and shuffle deck of cards example
+12.5k Golang : Convert int(year) to time.Time type
+11.4k How to tell if a binary(executable) file or web application is built with Golang?
+6.7k Golang : Normalize email to prevent multiple signups example