Get the App
SLTechnology News&Howtos  ›  Development  › 

How to intercept Chinese and English strings encoded by utf8 or gbk by php

Shulou Source: shulou.com Published: 2022-06-03 15:44:39 10月01日 Update

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)

Tags: Characters coding Chinese English string code learning half-width word count more demand full-width help limitation practical next no two hello parameters Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MariaDB macOS Shulou Information Docker Shulou Technology