This article mainly introduces to you the specific implementation method of PHP counting the number of occurrences of each character in a string..
PHP counts the number of character repetitions, which is also one of the common questions in PHP interview questions. It may be difficult for novices. Below we will use specific code examples to introduce in detail the method of counting the number of occurrences of characters in PHP. We hope it will help everyone learn and understand relevant knowledge points.
<?php /** * PHP 统计字符重复次数和字符 */ echo '<pre class="brush:php;toolbar:false">'; $str = 'aaaaabbbbbcccss';//字符串示例 echo $str . '<br/>'; //把出现过的字符记录在此数组中,如果记录有,则不记录 $strRecord = array(); for ($i = 0; $i < strlen($str); $i++) { //默认设置为没有遇到过 $found = 0; foreach ($strRecord as $k => $v) { if ($str[$i] == $v['key']) { //记录再次遇到的字符,count + 1; $strRecord[$k]['count'] += 1; //设置已经遇到过的,标记 $found = 1; //如果已经遇到,不用再循环记录数组了,继续下一个字符串比较 break; } } if (!$found) { //记录第一次遇到的字符,count + 1; $strRecord[] = array('key' => $str[$i], 'count' => 1); } } //print_r($strRecord); $str2 = ''; foreach ($strRecord as $k => $v) { foreach ($v as $key => $value) { $str2 .= $value; } } echo $str2; ?>
The result of counting the number of times each repeated element in the string is as shown below:
As shown in the figure, we successfully count the number of times each character is repeated. .
Then in the above code, the meaning of each step of the main code is also introduced in the form of comments. I hope it will help everyone understand and learn.
This article is an introduction to the specific method of counting the number of occurrences of each character in a string in PHP. I hope it will be helpful to friends in need!
If you want to know more about PHP, you can follow the PHP Chinese website PHP Video Tutorial, everyone is welcome to refer to and learn!
The above is the detailed content of How to count the number of repeated characters in PHP? (Pictures + Videos). For more information, please follow other related articles on the PHP Chinese website!