首頁  >  文章  >  後端開發  >  php傳回字串所有資訊的函數count_chars()

php傳回字串所有資訊的函數count_chars()

黄舟
黄舟原創
2017-11-02 10:20:101633瀏覽

實例

傳回一個字串,包含所有在"Hello World!" 中使用過的不同字元(模式3):

<?php
$str = "Hello World!";
echo count_chars($str,3);
?>

定義和用法

count_chars() 函數傳回字串所用字元的資訊(例如,ASCII 字元在字串中出現的次數,或某個字元是否已經在字串中使用過)。

文法

count_chars(string,mode)

參數                       說明

#string              規定要檢查的字串。    

mode                      選擇。規定返回模式。預設是 0。有以下不同的回傳模式:

                               0 - 陣列# #             1 - 數組,ASCII 值為鍵名,出現的次數為鍵值,只列出出現次數大於0 的值

                               2 - 陣列,ASCII 值為鍵名,出現時的次數為鍵值,

##                               3 - 字串,並使用所有使用過的不同的字元

# #  帶有所有未使用過的不同的字元

技術細節

傳回值:       取決於指定的 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>&#39;".chr($key)."&#39;</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.

以上是php傳回字串所有資訊的函數count_chars()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn