大网数据广告活动
PHP 语言与运行手册

count_chars · 返回字符串所用字符的信息

· 52CE 我爱测

根据不同的 mode,count_chars() 返回下列不同的结果: 0 - 以所有的每个字节值作为键名,出现次数作为值的数组。

count_chars

(PHP 4, PHP 5, PHP 7, PHP 8)

count_chars — 返回字符串所用字符的信息

说明

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

统计 string 中每个字节值(0..255)出现的次数,使用多种模式返回结果。

参数

string

需要统计的字符串。

mode

参见返回的值。

返回值

根据不同的 mode,count_chars() 返回下列不同的结果:

  • 0 - 以所有的每个字节值作为键名,出现次数作为值的数组。

  • 1 - 与 0 相同,但只列出出现次数大于零的字节值。

  • 2 - 与 0 相同,但只列出出现次数等于零的字节值。

  • 3 - 返回由所有使用了的字节值组成的字符串。

  • 4 - 返回由所有未使用的字节值组成的字符串。

更新日志

版本 说明
8.0.0 在此版本之前,函数在失败时返回 false。

示例

示例 #1 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.\n";
}
?>

以上示例会输出:

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 Documentation Group · 作者与贡献记录 · CC BY 3.0。离线整理了版式、链接和媒体显示。

资料来源与适用范围

资料来源
PHP Documentation Group
适用范围
请按文中版本与环境说明核对
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。