count_chars

(PHP 4, PHP 5, PHP 7, PHP 8)

count_chars返回字符串所用字符的信息

說明

count_chars(string $string, int $mode = 0): mixed

統(tǒng)計 string 中每個字節(jié)值(0..255)出現(xiàn)的次數(shù),使用多種模式返回結(jié)果。

參數(shù)

string

需要統(tǒng)計的字符串。

mode

參見返回的值。

返回值

根據(jù)不同的 mode,count_chars() 返回下列不同的結(jié)果:

  • 0 - 以所有的每個字節(jié)值作為鍵名,出現(xiàn)次數(shù)作為值的數(shù)組。
  • 1 - 與 0 相同,但只列出出現(xiàn)次數(shù)大于零的字節(jié)值。
  • 2 - 與 0 相同,但只列出出現(xiàn)次數(shù)等于零的字節(jié)值。
  • 3 - 返回由所有使用了的字節(jié)值組成的字符串。
  • 4 - 返回由所有未使用的字節(jié)值組成的字符串。

范例

示例 #1 count_chars() 示例

<?php
$data 
"Two Ts and one F.";

foreach (
count_chars($data1) as $i => $val) {
   echo 
"There were $val instance(s) of \"" chr($i) , "\" in the string.\n";
}
?>

以上例程會輸出:

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.

參見

  • strpos() - 查找字符串首次出現(xiàn)的位置
  • substr_count() - 計算字串出現(xiàn)的次數(shù)