How to count the number of repeated characters in PHP? (Pictures + Videos)

藏色散人
Release: 2018-10-16 09:35:25
Original
5980 people have browsed it

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 &#39;<pre class="brush:php;toolbar:false">&#39;;
$str = &#39;aaaaabbbbbcccss&#39;;//字符串示例
echo $str . &#39;<br/>&#39;;
//把出现过的字符记录在此数组中,如果记录有,则不记录
$strRecord = array();
for ($i = 0; $i < strlen($str); $i++) {
    //默认设置为没有遇到过
    $found = 0;
    foreach ($strRecord as $k => $v) {
        if ($str[$i] == $v[&#39;key&#39;]) {
            //记录再次遇到的字符,count + 1;
            $strRecord[$k][&#39;count&#39;] += 1;
            //设置已经遇到过的,标记
            $found = 1;
            //如果已经遇到,不用再循环记录数组了,继续下一个字符串比较
            break;
        }
    }
    if (!$found) {
        //记录第一次遇到的字符,count + 1;
        $strRecord[] = array(&#39;key&#39; => $str[$i], &#39;count&#39; => 1);
    }
}

//print_r($strRecord);
$str2 = &#39;&#39;;
foreach ($strRecord as $k => $v) {
    foreach ($v as $key => $value) {
        $str2 .= $value;
    }

}
echo $str2;
?>
Copy after login

The result of counting the number of times each repeated element in the string is as shown below:

How to count the number of repeated characters in PHP? (Pictures + Videos)

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!

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