PHP - count_chars() 函式



PHP 的 count_chars() 函式用於檢索關於字串中使用的字元的資訊。

此函式接受一個名為“mode”的引數,該引數包含各種值(即 0、1、2、3)。如果 mode 值為 0、1 或 2,它將返回一個數組。如果 mode 值為 3,它將返回一個字串,其中包含輸入字串中所有唯一的字元。

語法

以下是 PHP count_chars() 函式的語法:

count_chars(string $str, int $mode = 0): array|string

引數

此函式接受以下引數:

  • str: 表示要檢查的字串。
  • mode: 確定返回何種資料的模式。

模式可以是以下值之一:

  • 模式 0(預設): 返回一個數組,其中位元組值為鍵,每個位元組的頻率為值。
  • 模式 1: 返回與模式 0 相同的資料,但只包含頻率大於零的位元組值。
  • 模式 2: 返回與模式 0 相同的資料,但只包含頻率等於零的位元組值。
  • 模式 3: 返回一個字串,其中包含所有唯一的字元(至少出現一次的字元),順序與它們在字串中首次出現的順序相同。

返回值

此函式返回一個數組(如果 $mode 為 0、1 或 2)或一個字串(如果 $mode 為 3)。

示例 1

如果在 PHP count_chars() 函式中省略 mode 引數,它將使用預設模式 0:

<?php
   $str = "Hi";
   echo "The given string is: $str";
   echo "\nThe info about characters: ";
   #using count_chars() function
   print_r(count_chars($str));
?>

輸出

以上程式產生以下輸出:

The given string is: Hi
The info about characters: Array
(
    [0] => 0
    [1] => 0
    [2] => 0
    [3] => 0
	.........
    [253] => 0
    [254] => 0
    [255] => 0
)

示例 2

傳遞兩個引數 (str, $mode = 1) 以檢索字串中字元資訊。

以下是使用 PHP count_chars() 函式的另一個示例。此函式用於使用模式值 1 檢索字串“Welcome to TP”中使用的字元資訊:

<?php
   $str = "Welcome to TP";
   echo "The given string is: $str\n";
   $mode = 1;
   echo "The given mode is: $mode";
   echo "\nThe characters info used in string: \n";
   foreach (count_chars($str, $mode) as $i => $val) {
      echo "There were $val instance(s) of \"".chr($i)."\" in the string.\n";
   }
?>

輸出

執行上述程式後,將顯示以下輸出:

The given string is: Welcome to TP
The given mode is: 1
The characters info used in string:
There were 2 instance(s) of " " in the string.
There were 1 instance(s) of "P" in the string.
There were 1 instance(s) of "T" in the string.
There were 1 instance(s) of "W" in the string.
There were 1 instance(s) of "c" in the string.
There were 2 instance(s) of "e" in the string.
There were 1 instance(s) of "l" in the string.
There were 1 instance(s) of "m" in the string.
There were 2 instance(s) of "o" in the string.
There were 1 instance(s) of "t" in the string.

示例 3

當您傳遞 mode = 3 時,它將返回一個包含輸入字串中所有唯一字元的“字串”,每個字元只出現“一次”,順序與它們在字串中首次出現的順序相同:

<?php
   $str = "Hello Word";
   echo "The given string is: $str";
   $mode = 3;
   echo "\nThe given mode is: $mode";
   echo "\nThe info about characters: ";
   #using count_chars() function
   var_dump(count_chars($str,$mode));
?>

輸出

以下是上述程式的輸出:

The given string is: Hello Word
The given mode is: 3
The info about characters: string(8) " HWdelor"
php_function_reference.htm
廣告