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
广告