返回一个字符串,包含所有在 "Hello World!" 中使用过的不同字符(模式 3):
<?php $str = "Hello World!"; echo count_chars($str,3); ?>
运行结果:
!HWdelor
count_chars() 函数返回字符串所用字符的信息(例如,ASCII 字符在字符串中出现的次数,或者某个字符是否已经在字符串中使用过)。
count_chars(string,mode)
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
mode | 可选。规定返回模式。默认是 0。有以下不同的返回模式:
|
返回值: | 取决于指定的 mode 参数。 |
---|---|
PHP 版本: | 4+ |
返回一个字符串,包含所有在 "Hello World!" 中未使用过的字符(模式 4):
<?php $str = "Hello World!"; echo count_chars($str,4); ?>
运行结果:
"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGIJKLMNOPQRSTUVXYZ[\]^_`abcfghijkmnpqstuvwxyz{|}~АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■
在本实例中,我们将使用 count_chars() 来检查字符串,返回模式设置为 1。模式 1 将返回一个数组,ASCII 值为键名,出现的次数为键值:
<?php $str = "Hello World!"; print_r(count_chars($str,1)); ?>
运行结果:
Array ( [32] => 1 [33] => 1 [72] => 1 [87] => 1 [100] => 1 [101] => 1 [108] => 3 [111] => 2 [114] => 1 )
统计 ASCII 字符在字符串中出现的次数另一个实例:
<?php $str = "PHP is pretty fun!!"; $strArray = count_chars($str,1); foreach ($strArray as $key=>$value) { echo "The character <b>'".chr($key)."'</b> was found $value time(s)<br>"; } ?>
运行结果:
The character ' ' was found 3 time(s) The character '!' was found 2 time(s) The character 'H' was found 1 time(s) The character 'P' was found 2 time(s) The character 'e' was found 1 time(s) The character 'f' was found 1 time(s) The character 'i' was found 1 time(s) The character 'n' was found 1 time(s) The character 'p' was found 1 time(s) The character 'r' was found 1 time(s) The character 's' was found 1 time(s) The character 't' was found 2 time(s) The character 'u' was found 1 time(s) The character 'y' was found 1 time(s)