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
+20.1k Golang : Convert(cast) string to rune and back to string example
+5.3k Golang : Map within a map example
+17.9k Golang : Check if directory exist and create if does not exist
+12.4k Golang : How to get year, month and day?
+5.9k Golang : constant 20013 overflows byte error message
+5.1k AWS S3 : Prevent Hotlinking policy
+4.7k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+11.6k Golang : Drop cookie to visitor's browser and http.SetCookie() example
+5k Golang : Calculate US Dollar Index (DXY)
+32.1k Golang : Converting a negative number to positive number
+11.5k Golang : How to calculate the distance between two coordinates using Haversine formula
+6k Golang : Get environment variable