[php] count_chars — 返回字符串所用字符的信息
統計 string 中每個字節值(0..255)出現的次數,使用多種模式返回結果。可選參數 mode 默認值為 0。根據不同的 mode,count_chars() 返回下列不同的結果:
- 0 - 以所有的每個字節值作為鍵名,出現次數作為值的數組。
- 1 - 與 0 相同,但只列出出現次數大於零的字節值。
- 2 - 與 0 相同,但只列出出現次數等於零的字節值。
- 3 - 返回由所有使用了的字節值組成的字符串。
- 4 - 返回由所有未使用的字節值組成的字符串。
官方範例
<?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";
}
?>
以上例程會輸出:
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.
範例一
在本例中,我們將使用 count_chars() 來檢查字符串,返回模式設置為 1:
<?php
$str = "Hello World!";
print_r(count_chars($str,1));
?>
輸出:
Array
(
[32] => 1
[33] => 1
[72] => 1
[87] => 1
[100] => 1
[101] => 1
[108] => 3
[111] => 2
[114] => 1
)
範例二
在本例中,我們將使用 count_chars() 來檢查字符串,返回模式設置為 3:
<?php
$str = "Hello World!";
echo count_chars($str,3);
?>
輸出:
!HWdelor