Home > Article > Backend Development > How to count the number of occurrences of a specified character in a string in PHP
This article mainly introduces how PHP counts the number of occurrences of specified characters in a string.
#PHP statistics calculates the number of specified characters and all characters in a string, which is also a common test point in the PHP interview process. So for PHP beginners, it may be difficult. But as long as you master the idea of implementing it, it is very simple.
Below we will use a simple example to introduce to you how to count the number of occurrences of a specified character in a string.
PHP code example is as follows:
<?php $text="php.cn"; $search_char="p"; $count="0"; for($x="0"; $x< strlen($text); $x++) { if(substr($text,$x,1)==$search_char) { $count=$count+1; } } echo '"'.$text.'"'."中字符".$search_char."出现的次数是:".$count.'次';
Here we calculate the number of times the letter p appears in the string php.cn, and the output result is as follows:
Of course we can count the number of times any one of the characters, such as h:
Related function introduction:
strlen function means getting the string length.
substr function means returning a substring of a string. Its syntax:
string substr ( string $string , int $start [, int $length ] )
Returns the string string substring specified by the start and length parameters.
This article is an introduction to the method of counting the number of occurrences of specified characters in a string in PHP. It is also very simple and easy to understand. I hope it will be helpful to friends in need!
The above is the detailed content of How to count the number of occurrences of a specified character in a string in PHP. For more information, please follow other related articles on the PHP Chinese website!