简体   繁体   English

PHP如何计算带有字母的字符串中每个字母的数量?

[英]PHP how can I count the amount of each letter in a string with letters?

How can I count the amount of each letter in a string with letters? 如何计算带有字母的字符串中每个字母的数量?

For example: 例如:

$string = "ababdcbadbcabcbcadcbadbc"

Now I have to count how many a's, b's, c's and d's are in the string and I have to print the result in a diagram. 现在,我必须计算字符串中有多少个a,b,c和d,并且必须将结果打印在图表中。

Tnx and keep programming! Tnx并继续编程! ;) ;)

Use array_count_values() 使用array_count_values()

$string = "ababdcbadbcabcbcadcbadbc";
print_r(array_count_values(str_split($string)));

OUTPUT :

Array
(
    [a] => 6
    [b] => 8
    [d] => 4
    [c] => 6
)

I have to print the result in a diagram 我必须在图表中打印结果

And here comes the lovely diagram! 这是可爱的图表!

array_multisort($arr);

foreach($arr as $k=>$v)
{
    echo str_repeat($k,$v)."<br>";
}

OUTPUT :

dddd
aaaaaa
cccccc
bbbbbbbb

See the full working demo 查看完整的工作演示

Look at this http://www.php.net/manual/en/function.count-chars.php 看看这个http://www.php.net/manual/en/function.count-chars.php

Hope that helps. 希望能有所帮助。 Let me know, if not. 让我知道,如果没有。

 <?php $data = "Two Ts and one F."; foreach (count_chars($data, 1) as $i => $val) { echo "There were $val instance(s) of \\"" , chr($i) , "\\" in the string.\\n"; } ?> 

Use this may be it will help you. 使用此功能可能会对您有所帮助。

print_r(array_count_values(str_split("string")));

Goodluck, Cheers. 祝你好运,干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM