计算X字符的数量

时间:2010-12-15 21:22:08

标签: php string

我正在尝试使用explode()失败的东西,所以我想尝试别的东西。如果我有一个字符串,我如何计算其中的字符数,例如comma中的,

2 个答案:

答案 0 :(得分:3)

尝试substr_count()

substr_count($text, ',');

答案 1 :(得分:1)

您可以使用count_chars

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";
}

输出(codepad):

There were 4 instance(s) of " " in the string.
There were 1 instance(s) of "." in the string.
There were 1 instance(s) of "F" in the string.
There were 2 instance(s) of "T" in the string.
There were 1 instance(s) of "a" in the string.
There were 1 instance(s) of "d" in the string.
There were 1 instance(s) of "e" in the string.
There were 2 instance(s) of "n" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "s" in the string.
There were 1 instance(s) of "w" in the string.