執行個體
返回一個字串,包含所有在 "Hello World!" 中使用過的不同字元(模式 3):
<?php$str = "Hello World!";echo count_chars($str,3);?>
定義和用法
count_chars() 函數返回字串所用字元的資訊(例如,ASCII 字元在字串中出現的次數,或者某個字元是否已經在字串中使用過)。
文法
count_chars(string,mode)
參數 描述
string 必需。規定要檢查的字串。
mode 可選。規定返回模式。預設是 0。有以下不同的返回模式:
0 - 數組,ASCII 值為鍵名,出現的次數為索引值
1 - 數組,ASCII 值為鍵名,出現的次數為索引值,只列出出現次數大於 0 的值
2 - 數組,ASCII 值為鍵名,出現的次數為索引值,只列出出現次數等於 0 的值
3 - 字串,帶有所有使用過的不同的字元
4 - 字串,帶有所有未使用過的不同的字元
技術細節
傳回值: 取決於指定的 mode 參數。
PHP 版本: 4+
更多執行個體
執行個體 1
返回一個字串,包含所有在 "Hello World!" 中未使用過的字元(模式 4):
<?php$str = "Hello World!";echo count_chars($str,4);?>
執行個體 2
在本執行個體中,我們將使用 count_chars() 來檢查字串,返回模式設定為 1。模式 1 將返回一個數組,ASCII 值為鍵名,出現的次數為索引值:
<?php$str = "Hello World!";print_r(count_chars($str,1));?>
執行個體 3
統計 ASCII 字元在字串中出現的次數另一個執行個體:
<?php$str = "PHP is pretty fun!!";$strArray = count_chars($str,1);foreach ($strArray as $key=>$value){echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>";}?>
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.<br/>" ;}?>
運行結果:
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.