算上所有的字母出现在一个字符串PHP [英] count the occurrences of all the letters in a string PHP
问题描述
我要计算一个字符串的所有字母出现的频率。说我有
$海峡=cdcdcdcdeeeef;
我可以使用str_split和array_count_values实现这一目标。
array_count_values(str_split($ STR));
想知道是否有另一种方式来做到这一点,而不串转换到一个数组?谢谢
您不必将其转换成阵列()
您可以使用 substr_count()
来实现相同的。
substr_count - 计数子出现的次数
块引用>< PHP
$海峡=cdcdcdcdeeeef;
回声substr_count($海峡,'C');
?>
substr_count()
返回草垛发生串针子的次数。请注意,针是大小写敏感的。编辑:
很抱歉的误解,可以使用
count_chars
有字符串中的每个字符的计数值。举个例子:< PHP
$海峡=cdcdcdcdeeeef;的foreach(count_chars($ STR,1)$ STRR => $值){
回声CHR($ STRR)。 串中发生了一些$值倍。 。 < BR>中;
}
?>
count_chars - 返回有关字符串中使用的字符信息
块引用>I want to count the frequency of occurrences of all the letters in a string. Say I have
$str = "cdcdcdcdeeeef";
I can use str_split and array_count_values to achieve this.
array_count_values(str_split($str));
Wondering if there is another way to do this without converting the string to an array? Thanks
解决方案You don't have to convert that into an
array()
you can usesubstr_count()
to achieve the same.substr_count — Count the number of substring occurrences
<?php $str = "cdcdcdcdeeeef"; echo substr_count($str, 'c'); ?>
substr_count()
returns the number of times the needle substring occurs in the haystack string. Please note that needle is case sensitive.EDIT:
Sorry for the misconception, you can use
count_chars
to have a counted value of each character in a string. An example:<?php $str = "cdcdcdcdeeeef"; foreach (count_chars($str, 1) as $strr => $value) { echo chr($strr) . " occurred a number of $value times in the string." . "<br>"; } ?>
count_chars — Return information about characters used in a string
这篇关于算上所有的字母出现在一个字符串PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!