Simple implementation method of counting the number of Chinese characters in PHP

怪我咯
Release: 2023-03-12 14:28:01
Original
1239 people have browsed it

This article mainly introduces the method of php to simply count the number of Chinese characters, involving strlen, mb_strlen and mb_strwidth and other functionsUsage methods and related Notes, friends in need can refer to

This article describes the simple method of counting the number of Chinese characters in PHP. I would like to share it with you for your reference. The details are as follows:

The previous company was engaged in foreign trade and all the data used were in English, so when counting the length, I used the strlen function, and there was always no error, but now the statistics are in Chinese. This went wrong, now do a recording test

<?php
echo strlen("你好ABC") . "";
# 输出 9
echo mb_strlen("你好ABC", &#39;UTF-8&#39;) . "";
# 输出 5
echo mb_strwidth("你好ABC") . "";
#输出 7
?>
Copy after login

From the above test, we can see:

strlen counts Chinese characters into 3 bytes

mb_strlen Regardless of Chinese or English, it is counted as 1 byte

mb_strwidth is counted as 2 bytes for Chinese

So use the mb_strlen function when calculating length

The above is the detailed content of Simple implementation method of counting the number of Chinese characters in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!