How to intercept Chinese and English strings encoded by utf8 or gbk by php
This article mainly introduces "how php intercepts Chinese and English strings encoded by utf8 or gbk". In daily operation, I believe many people have doubts about how to intercept Chinese and English strings encoded by utf8 or gbk. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the questions of "how to intercept Chinese and English strings encoded by utf8 or gbk by php". Next, please follow the editor to study!
Weibo's speech has a word limit, which is counted as two in Chinese, one in English, two in full-width characters and one in half-width characters.
The number of bytes returned with strlen in php is 3 when it is returned in Chinese encoded by utf8, which does not meet the demand.
Mb_strlen can calculate the length according to the character set. For example, utf8 has a Chinese count of 1, but this does not meet the Weibo word limit. Chinese must be calculated as 2.
Google, found a discuz to intercept a variety of encoded characters of the class, under the transformation, has been tested. The parameter $charset only supports gbk and utf-8.
The copy code is as follows:
$a = "Hello @ Hello"; var_dump (strlen_weibo ($a memory utf Mel 8')
The result is 8, where the letter s count is 1, the full-width @ count is 2, the half-width @ count is 1, and the two Chinese counts are 4. The source code is as follows
The copy code is as follows:
Function strlen_weibo ($string, $charset='utf-8') {$n = $count = 0; $length = strlen ($string); if (strtolower ($charset) = = 'utf-8') {while ($n < $length) {$currentByte = ord ($string [$n]); if ($currentByte = = 9 | $currentByte = = 10 | | (32)