count_chars

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

count_chars返回字符串中使用的字符信息

描述

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

统计 string 中每个字节值(0..255)出现的次数,并以各种方式返回结果。

参数

string

要检查的字符串。

mode

参见返回值。

返回值

根据 modecount_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.

参见

  • strpos() - 在字符串中查找子字符串首次出现的位置
  • substr_count() - 统计子字符串出现的次数

添加注释

用户贡献的注释 11 条注释

24
marcus33cz
12 年前
如果您在使用多字节字符串时遇到 count_chars 问题,您可以更改页面编码。或者,您也可以使用此 mb_count_chars 版本的函数。基本上它是原始函数的“1”模式。

<?php
/**
* 统计多字节字符串中的字符出现次数
* @param string $input UTF-8 数据
* @return array 字符的关联数组。
*/
function mb_count_chars($input) {
$l = mb_strlen($input, 'UTF-8');
$unique = array();
for(
$i = 0; $i < $l; $i++) {
$char = mb_substr($input, $i, 1, 'UTF-8');
if(!
array_key_exists($char, $unique))
$unique[$char] = 0;
$unique[$char]++;
}
return
$unique;
}

$input = "Let's try some Greek letters: αααααΕεΙιΜμΨψ, Russian: ЙЙЫЫЩН, Czech: ěščřžýáíé";
print_r( mb_count_chars($input) );
//returns: Array ( [L] => 1 [e] => 7 [t] => 4 ['] => 1 [s] => 5 [ ] => 9 [r] => 3 [y] => 1 [o] => 1 [m] => 1 [G] => 1 [k] => 1 [l] => 1 [:] => 3 [α] => 5 [Ε] => 1 [ε] => 1 [Ι] => 1 [ι] => 1 [Μ] => 1 [μ] => 1 [Ψ] => 1 [ψ] => 1 [,] => 2 [R] => 1 [u] => 1 [i] => 1 [a] => 1 [n] => 1 [Й] => 2 [Ы] => 2 [Щ] => 1 [Н] => 1 [C] => 1 [z] => 1 [c] => 1 [h] => 1 [ě] => 1 [š] => 1 [č] => 1 [ř] => 1 [ž] => 1 [ý] => 1 [á] => 1 [í] => 1 [é] => 1 )
?>
2
Eric Pecoraro
19 年前
<?php

// 在字符串中需要 (n) 个唯一字符
// 对下面函数的修改,在给定字符串中需要多少个唯一字符方面增加了灵活性。

$pass = '123456' ; // true
$pass = '111222' ; // false

req_unique($pass,3);

function
req_unique($string,$unique=3) {
if (
count(count_chars($string,1)) < $unique) {
echo
'false';
}else{
echo
'true';
}
}

?>
1
seb at synchrocide dot net
20 年前
经过多次尝试和错误,试图创建一个函数来查找字符串中唯一字符的数量,我找到了 count_chars() - 我 20 多行无用的代码被它取代了。

<?
function unichar($string) {
$two= strtolower(str_replace(' ', '', $string));
$res = count(count_chars($two, 1));
return $res;
}

/* 例子 :: */

echo unichar("bob"); // 2
echo unichar("Invisibility"); //8
echo unichar("The quick brown fox slyly jumped over the lazy dog"); //26

?>

我不知道它可以在哪里使用,但它很有趣。
0
匿名
8 年前
count_chars 支持多字节。

<?php

function mb_count_chars ($string, $mode = 0) {

$result = array_fill(0, 256, 0);

for (
$i = 0, $size = mb_strlen($string); $i < $size; $i++) {
$char = mb_substr($string, $i, 1);
if (
strlen($char) > 1) {
continue;
}

$code = ord($char);
if (
$code >= 0 && $code <= 255) {
$result[$code]++;
}
}

switch (
$mode) {
case
1: // same as 0 but only byte-values with a frequency greater than zero are listed.
foreach ($result as $key => $value) {
if (
$value == 0) {
unset(
$result[$key]);
}
}
break;
case
2: // same as 0 but only byte-values with a frequency equal to zero are listed.
foreach ($result as $key => $value) {
if (
$value > 0) {
unset(
$result[$key]);
}
}
break;
case
3: // a string containing all unique characters is returned.
$buildString = '';
foreach (
$result as $key => $value) {
if (
$value > 0) {
$buildString .= chr($key);
}
}
return
$buildString;
case
4: // a string containing all not used characters is returned.
$buildString = '';
foreach (
$result as $key => $value) {
if (
$value == 0) {
$buildString .= chr($key);
}
}
return
$buildString;
}

// change key names...
foreach ($result as $key => $value) {
$result[chr($key)] = $value;
unset(
$result[$key]);
}

return
$result;

}
?>
-1
Andrey G
4 years ago
检查两个字符串是否为变位词

<?php

function isAnagram($string1, $string2)
{
return
count_chars($string1, 1) === count_chars($string2, 1);
}

isAnagram('act', 'cat'); // true

?>
-1
pzb at novell dot com
17 years ago
此函数非常适合输入验证。我经常需要检查字符串中的所有字符是否为 7 位 ASCII(而不是空)。这是我迄今为止找到的最快函数

<?php
function is7bit($string) {
// 空字符串是 7 位干净的
if (!strlen($string)) {
return
true;
}
// count_chars 按升序八位字节顺序返回字符
$str = count_chars($str, 3);
// 检查空字符
if (!ord($str[0])) {
return
false;
}
// 检查 8 位字符
if (ord($str[strlen($str)-1]) & 128) {
return
false;
}
return
true;
}
?>
-3
phpC2007
16 years ago
这是一个用于统计字符串中字符串数量的函数。它可以用作简单的 utf8 启用 count_chars(但仅限于单一模式)...

<?php
function utf8_count_strings($stringChar)
{
$num = -1;
$lenStringChar = strlen($stringChar);

for (
$lastPosition = 0;
$lastPosition !== false;
$lastPosition = strpos($textSnippet, $stringChar, $lastPosition + $lenStringChar))
{
$num++;
}

return
$num;
}
?>
-6
qeremy [atta] gmail [dotta] com
11 years ago
另一种统计 Unicode 字符的方法。

<?php
function count_chars_unicode($str, $x = false) {
$tmp = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY);
foreach (
$tmp as $c) {
$chr[$c] = isset($chr[$c]) ? $chr[$c] + 1 : 1;
}
return
is_bool($x)
? (
$x ? $chr : count($chr))
:
$chr[$x];
}

$str = "şeker şeker yâriiiiiiiiiimmmmm";
print_r(count_chars_unicode($str, 'â')); // frequency of "â"
print_r(count_chars_unicode($str)); // count of uniq chars
print_r(count_chars_unicode($str, true)); // all chars with own frequency
?>

输出;
1
9
数组
(
[ş] => 2
[e] => 4
[k] => 2
[r] => 3
[ ] => 2
[y] => 1
[â] => 1
[i] => 10
[m] => 5
)
-5
mlong at mlong dot org
22 years ago
// 这两个函数的用处

<?php
$string
="aaabbc";

// 只想统计字母 a 的数量
$acount=substr_count($string,"a");

// 想同时统计字母 a 和字母 b 的数量
$counts=count_chars($string,0);
$acount=$counts[ord("a")];
$bcount=$counts[ord("b")];
?>
-7
maotin at hongkong dot com
23 年前
以下是关于这个相对较新且非常实用的函数的一些更多实验。

<?php
$string
= 'I have never seen ANYTHING like that before! My number is "4670-9394".';

foreach(
count_chars($string, 1) as $chr => $hit)
echo
'The character '.chr(34).chr($chr).chr(34).' has appeared in this string '.$hit.' times.<BR>';

#The result looks like
#The character " " has appeared in this string 11 times.

echo count_chars($string,3);
#The output is '!"-.034679AGHIMNTYabefhiklmnorstuvy'

echo strlen($string).' is not the same as '.strlen(count_chars($string, 3));

#This shows that '70 is not the same as 36'
?>

正如我们在上面看到的

1) 如果你只关心字符串中有什么,使用 count_chars($string, 1),它将返回一个(关联?)数组,其中只包含出现过的内容。

2) 要么是我误解了手册中实际描述的内容,要么它没有按照描述的方式工作:count_chars($strting, 3) 实际上返回的是字符串中有哪些字符的字符串,而不是它们的字节值的字符串(这很棒,因为数字字符串将更难处理);

3) 这是一个简短的密码检查版本:获取原始字符串的长度,然后将其与 count_chars($string,3) 返回的字符串长度进行比较。

<?php
$length_of_string
= strlen($string);
$num_of_chars = strlen(count_chars($string, 3));

$diff = ($length_of_string - $num_of_chars);

if (
$diff)
echo
'At least one character has been used more than once.';
else
echo
'All character have been used only once.';
?>

请注意,由于 $num_of_chars 不会提供有关实际出现次数的信息,因此我们无法用相同的推理进一步推断,例如,当 $diff = 2 时,表示两个字符出现了两次;它可能是 1 个字符出现了 3 次,我们无法确定(不过,这是一个很好的容差级别设置器)。如果你想获得更多控制权,你需要获取数组并检查值。

4) 最后一个小技巧:现在我们有了一种原始的方法来计算字符串中单词的数量!(或者我们已经有一个函数可以做到这一点?)
-12
apinpratap at gmail dot com
17 years ago
这段代码可以找到每个字符的计数

<?php
$enter
= 0;
$data = strtolower ($inputString);
foreach (
count_chars ($data, 1) as $i => $val)
{
if (
$enter == 1)
{
$enter = 0;
continue;
}
if (
chr ($i) == "\n")
{
echo
"There are $val instance(s) of \" Enter \" in the string.\n";
$enter = 1;
}
else
{
echo
"There are $val instance(s) of \"" , chr ($i) , "\" in the string.\n";
}
}
?>
To Top