How to calculate the length of Chinese and English strings using PHP functions, _PHP tutorial

WBOY
Release: 2016-07-13 10:14:30
Original
785 people have browsed it

How to calculate the length of Chinese and English strings using PHP functions,

The example in this article describes how to use PHP functions to calculate the length of Chinese and English strings. Share it with everyone for your reference. The specific implementation method is as follows:

Generally speaking, everyone knows that English characters occupy one byte, while Chinese characters gbk occupies two characters, and utf8 occupies three characters. Many people think that PHP calculates the length of a string using the strlen() function. In fact, it does not. is the length of bytes rather than the length of characters, so how to get the length of characters in a string? There is also mb_strlen().

The specific code is as follows:

Copy code The code is as follows:
echo $str = 'PHP Diandiantong';

echo strlen($str); //3*1+3*3=12
echo mb_strlen($str, 'gb2312'); //3*1+3*2=9
echo mb_strlen($str, 'utf-8'); //6


What's terrible is that the functions of the mb series are not PHP core functions and are not enabled by default. There is also a super simple method to decompose the string into individual characters through regular expressions. Calculating the number of characters is the length of the string. The code As follows:
Copy code The code is as follows:
function _strlen($str)
{
Preg_match_all("/./us", $str, $matches);
          return count(current($matches));
}

echo _strlen("PHP Diandiantong"); //6
?>

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/909334.htmlTechArticleHow to use PHP functions to calculate the length of Chinese and English strings. This article describes the use of PHP functions to calculate the length of Chinese and English strings. length method. Share it with everyone for your reference. Specific implementation method...
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!