计算字符串PHP中所有字母的出现

Wil*_*dow 2 php arrays string

我想计算一个字符串中所有字母的出现频率。说我有

$str = "cdcdcdcdeeeef";
Run Code Online (Sandbox Code Playgroud)

我可以使用str_split和array_count_values实现此目的。

array_count_values(str_split($str));
Run Code Online (Sandbox Code Playgroud)

想知道是否还有另一种方法可以将字符串转换为数组吗?谢谢

Dir*_*Bit 5

您不必将其转换为array()可用于substr_count()实现相同目的的。

substr_count —计算子字符串出现的次数

<?php
$str = "cdcdcdcdeeeef";
echo substr_count($str, 'c'); 
?>
Run Code Online (Sandbox Code Playgroud)

PHP手册

substr_count()返回在干草堆字符串中出现针状子字符串的次数。请注意,针头区分大小写。

编辑:

对不起,您可能会误以为count_chars是一个字符串中每个字符的计数值。一个例子:

<?php
$str = "cdcdcdcdeeeef";

foreach (count_chars($str, 1) as $strr => $value) {
   echo chr($strr) . " occurred a number of $value times in the string." . "<br>";
}
?>
Run Code Online (Sandbox Code Playgroud)

PHP手册:count_chars

count_chars —返回有关字符串中使用的字符的信息