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
+16.5k CodeIgniter/PHP : Create directory if does not exist example
+29.7k Golang : How to create new XML file ?
+9.8k Golang : Populate slice with sequential integers example
+6.9k Golang : Reverse by word
+15.1k Golang : Basic authentication with .htpasswd file
+14.7k Golang : How to determine if user agent is a mobile device example
+8.7k Linux/Unix : fatal: the Postfix mail system is already running
+7.1k Nginx : Password protect a directory/folder
+20.7k Golang : Pipe output from one os.Exec(shell command) to another command
+15.5k Golang : Delete certain files in a directory
+18.2k Golang : Get all upper case or lower case characters from string example
+7.1k Golang : Normalize email to prevent multiple signups example