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
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+17.1k Google Chrome : Your connection to website is encrypted with obsolete cryptography
+13.2k Golang : Linear algebra and matrix calculation example
+18.4k Golang : Find IP address from string
+11.9k Golang : Perform sanity checks on filename example
+23.7k Golang : Use regular expression to validate domain name
+22.6k Golang : Round float to precision example
+30.7k Golang : Interpolating or substituting variables in string examples
+5.4k Clean up Visual Studio For Mac installation failed disk full problem
+15.8k Golang : Get file permission
+5k Golang : Customize scanner.Scanner to treat dash as part of identifier
+6.9k Golang : Takes a plural word and makes it singular