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

來源:互聯網
上載者:User

執行個體

返回一個字串,包含所有在 "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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.