php count the number of different types of characters in an article

user:visitors Date:2022-01-31 16:34:101270

An article consists of many different elements such as numbers, Chinese, letters, symbols, etc. If you need to count them, if you count them one by one, it will be a very troublesome thing, and it is easy to count wrong, so how? Use a common php program to automatically calculate and count the number of common different types of characters in an article for us?

Suppose there is an article here, and we store its content in the variable $wzwz.

$wzwz="XXX text content: sequence 1, 2, 3, 4, 5...";

1. The total number of characters in the article

<?php

echo $zong="The total number of characters is: ".mb_strlen($wzwz,'utf-8');

?>

In the php program, there is a strlen function that can quickly count the length of characters in a string, but why is strlen not used here?

Although strlen can get the character length, it will be considered as 2 characters when calculating Chinese, so here we have to use the mb_strlen function extended by mbstring in php.

The mb_strlen function can calculate Chinese characters well and set the character encoding to return the corresponding number of characters more accurately.

2, the number of numbers

<?php

$zhengze="/[0-9]{1}/";

preg_match_all($zhengze,$wzwz,$shuzi);

echo $shu="Number of numbers is: ".count($zhengze[0]);

?>

If we need to count the number of digits, we first need to filter all other characters with regularity, leaving only the digits, and then calculate the number of characters left by count.

3. Number of Chinese characters

<?php

$zhengze="/[\x{4e00}-\x{9fa5}]/siu";

preg_match_all($zhengze,$wzwz,$shuzi);

echo $zhong="The number of Chinese characters is: ".count($zhengze[0]);

?>

The method of calculating the number of Chinese characters is the same as the method of calculating the number of numbers. It is necessary to use regular expressions to obtain a simple array of Chinese characters. Then the number of Chinese characters can be calculated by counting the array.

4. Number of letters

<?php

$zhengze="/[a-zA-Z]{1}/";

preg_match_all($zhengze,$wzwz,$shuzi);

echo $zimu="The number of letters is: ".count($zhengze[0]);

?>

In the same way, just replace the regular with the regular of the uppercase and lowercase letters in an article, so as to count the number of words in the article.

5, the number of characters in the symbol

<?php

$fuhao = $zong-$shu-$zhong-$zimu;

?>

The acquisition of symbols is relatively simple, we only need to subtract the number of numbers, Chinese and letters from the total number of characters obtained to roughly calculate the number of symbols in the article.

The above is how to use php code to perform simple calculation and statistics on the number of characters of different text types in a text.

Popular articles
latest article