PHP's handling of Chinese strings has been plagued by novice programmers who have just come in contact with PHP development. The following is a brief analysis of the Chinese string length of PHP processing:
PHP comes with functions such as strlen (), Mb_strlen () that count the length of the string by calculating the number of bytes in the string, and one English character takes up 1 bytes. Cases:
$enStr = ' hello,china! ';
echo strlen ($ENSTR); Output: 12
But Chinese is not, do Chinese website generally choose two kinds of code: gbk/gb2312 or Utf-8. Utf-8 can be compatible with more characters, so it is loved by many stationmaster. GBK and Utf-8 are different in encoding Chinese, resulting in a difference in the number of bytes between GBK and Utf-8 encoding.
GBK encodes a byte of 2 for each Chinese character, for example:
$zhStr = ' Hello, China! ';
echo strlen ($ZHSTR); Output: 12
Utf-8 encodes a byte of 3 for each Chinese character, for example:
$zhStr = ' Hello, China! ';
echo strlen ($ZHSTR); Output: 18
So how do you calculate the length of this set of Chinese strings? One might say that GBK gets the Chinese string length divided by the 2,utf-8 code divided by 3 is it okay? But you have to consider the string is not honest, 99% of the situation will be mixed in the Sino-British situation.
This is a piece of code in WordPress, the main idea is to use the first time to decompose the string into individual units, and then calculate the number of cells that is the length of the string, the code is as follows (only UTF-8 encoded strings can be processed):
Copy Code code as follows:
$zhStr = ' Hello, China! ';
$str = ' Hello, China! ';
Calculate Chinese string length
function Utf8_strlen ($string = null) {
To decompose a string into cells
Preg_match_all ("/./us", $string, $match);
Return number of cells
return count ($match [0]);
}
echo Utf8_strlen ($ZHSTR); Output: 6
echo Utf8_strlen ($STR); Output: 9
utf8_strlen– gets the length of the UTF8 encoded string
Copy Code code as follows:
/*
* for UTF8 coded program
* Get string length, one Chinese for 3 lengths
* Itlearner Comment
* *
Function Utf8_strlen ($str) {
$count = 0;
for ($i = 0; $i < strlen ($STR); $i + +) {
$value = ord ($str [$i]);
if ($value > 127) {
$count + +;
if ($value >= && $value <= 223) $i + +;
ElseIf ($value >= 224 && $value <= 239) $i = $i + 2;
ElseIf ($value >= && $value <= 247) $i = $i + 3;
Else die (' Not a UTF-8 compatible string ');
}
$count + +;
}
Return $count;
}