In php, strlen is the number of returned bytes. Three UTF-8 encoded Chinese characters are returned, which does not meet the requirements. The following provides a method to complete this function.
In php, strlen is the number of returned bytes. Three UTF-8 encoded Chinese characters are returned, which does not meet the requirements. The following provides a method to complete this function.
Weibo's speech has a limit on the number of words. The count method is to count two Chinese characters, one English character, two full-width characters, and one half-width character.
In php, strlen is the number of returned bytes. Three UTF-8 encoded Chinese characters are returned, which does not meet the requirements.
Mb_strlen can be used to calculate the Length Based on the character set. For example, the Chinese count of utf8 is 1, but this does not meet the word limit on Weibo. It must be calculated as 2.
Google finds a class that intercepts various encoding characters in discuz. After transformation, it has passed the test. The $ charset parameter only supports gbk and UTF-8.
The Code is as follows:
$ A = "s @ ";
Var_dump (strlen_weibo ($ a, 'utf-8 '));
The result output is 8, where the letter s is counted as 1, the full @ count is 2, the half @ count is 1, and the two Chinese counts are 4. The source code is as follows:
The 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 <= $ currentByte & $ currentByte <= 126 ))
{
$ N ++;
$ Count ++;
} Elseif (194 <=$ currentByte & $ currentByte <= 223)
{
$ N + = 2;
$ Count + = 2;
} Elseif (224 <=$ currentByte & $ currentByte <= 239)
{
$ N + = 3;
$ Count + = 2;
} Elseif (240 <=$ currentByte & $ currentByte <= 247)
{
$ N + = 4;
$ Count + = 2;
} Elseif (248 <=$ currentByte & $ currentByte <= 251)
{
$ N + = 5;
$ Count + = 2;
} Elseif ($ currentByte = 252 | $ currentByte = 253)
{
$ N + = 6;
$ Count + = 2;
} Else
{
$ N ++;
$ Count ++;
}
If ($ count> = $ length)
{
Break;
}
}
Return $ count;
} Else
{
For ($ I = 0; $ I <$ length; $ I ++)
{
If (ord ($ string [$ I])> 127)
{
$ I ++;
$ Count ++;
}
$ Count ++;
}
Return $ count;
}
}