PHP statistics Chinese string length string to numeric PHP split string php string length ph

Source: Internet
Author: User
Chinese websites generally choose two types of code: gbk/gb2312 or Utf-8.
Each Chinese character in the GBK encoding occupies 2 bytes, as an example:

$zhStr = ‘您好,中国!’;echo strlen($zhStr// 输出:12
utf-8编码下每个中文字符所占字节为3,例:
$zhStr = ‘您好,中国!’;echo strlen($zhStr// 输出: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 = ‘您好,中国!’;$str = ‘Hello,中国!’;// 计算中文字符串长度functionutf8_strlen($string = null) {// 将字符串分解为单元$string$match);// 返回单元个数return count($match[0]);}echo utf8_strlen($zhStr// 输出:6echo utf8_strlen($str// 输出:9

Below I encapsulate a function to accurately calculate the length of the Chinese string:

functioncount_strlen($string = null){$fileType = mb_detect_encoding($stringarray('UTF-8','GBK','LATIN1','BIG5'//判断字符串中文编码的类型$length = iconv_strlen($string,$fileType);//根据字符编码计算字符串长度return$length;}$str"中文45汶";$len = count_strlen($str);echo$len//输出5

'). addclass (' pre-numbering '). Hide (); $ (this). addclass (' has-numbering '). Parent (). append ($numbering); for (i = 1; i <= lines; i++) {$numbering. Append ($ ('
  • '). Text (i)); }; $numbering. FadeIn (1700); }); });

    The above describes the PHP statistics Chinese string length, including the string, PHP content, I hope to be interested in PHP tutorial friends helpful.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.