Today I learned the PHP function to intercept Chinese strings, English strings, the use of the function of the string in English. Do not understand the Chinese and English interception methods, the first record here.
PHP's own functions, such as strlen (), Mb_strlen (), count the length of the string by calculating the number of bytes that the string occupies, and an English character is 1 bytes. Cases:
$enStr = ' hello,china! ';
echo strlen ($ENSTR); Output: 12
But Chinese is not, do Chinese website generally will choose two kinds of code: gbk/gb2312 or Utf-8. Utf-8 can be compatible with more characters, so it is loved by many webmasters. GBK and Utf-8 have different codes for Chinese, resulting in a difference in the number of bytes in the GBK and utf-8 codes.
Each Chinese character in the GBK encoding occupies 2 bytes, as an example:
$zhStr = ' Hello, China! ’;
echo strlen ($ZHSTR); Output: 12
Each Chinese character in the Utf-8 encoding occupies 3 bytes, as an 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 GBK to get the Chinese string length divided by the 2,utf-8 code divided by 3 isn't it OK? However, you have to consider the string is not honest, 99% of the situation will be mixed in the Chinese and English situation.
This is a piece of code in WordPress, the main idea is to first use the regular string decomposition into an individual unit, and then calculate the number of units is the length of the string, the code is as follows (only the string under the Utf-8 encoding):
$zhStr = ' Hello, China! ’;
$str = ' Hello, China! ’;
Calculating Chinese string Lengths
function Utf8_strlen ($string = null) {
To decompose a string into a cell
Preg_match_all ("/./us", $string, $match);
Returns the number of units
return count ($match [0]);
}
echo Utf8_strlen ($ZHSTR); Output: 6
echo Utf8_strlen ($STR); Output: 9
PHP intercepts Chinese string, English string, English string length method