count_chars()

1. 定义

返回指定字符串中,每个字节值出现的次数数组。

2. 语法

count_chars ( string $string [, int $mode = 0 ] ) : mixed

3. 参数说明

参数 可选性 数据类型 描述
$string 必需 字符串或数组 要检查的字符串
$mode 可选 整型 需要返回的值

其中$mode有5种可能的值:

  • 0:以所有的每个字节值作为键名,出现次数作为值的数组
  • 1:出现次数大于零的字节值数组
  • 2:出现次数等于零的字节值数组
  • 3:返回由所有使用了的字节值组成的字符串
  • 4:返回由所有未使用的字节值组成的字符串

4. 示例

<?php

// count_chars()
// 返回指定字符串中,每个字节值出现的次数数组。

$str = 'hello, world!';
$res = count_chars($str, 1);
var_dump($res);
/* 输出:
array(10) {
  [32]=>
  int(1)
  [33]=>
  int(1)
  [44]=>
  int(1)
  [100]=>
  int(1)
  [101]=>
  int(1)
  [104]=>
  int(1)
  [108]=>
  int(3)
  [111]=>
  int(2)
  [114]=>
  int(1)
  [119]=>
  int(1)
}
*/
$str = 'jisu';
$res = count_chars($str, 3);// 返回由所有使用了的字节值组成的字符串
var_dump($res);// 输出:string(4) "ijsu"

5. 延展阅读

  • strpos():查找特定子字符串首次出现的位置索引值(从 0 开始)
  • substr_count():返回指定子字符串在字符串中出现的次数