Php intercepts UTF-8 or gbk encoded Chinese and English strings
-
// String truncation
- $ 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:
-
// Extract the function code of the string
- 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) // bbs.it-home.org
- {
- $ 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;
- }
- }
|