PHP count_chars() 函数
实例
返回一个字符串,包含所有在 "Hello World!" 中使用过的不同字符(模式 3):
<?php $str = "Hello World!"; echo count_chars($str,3); ?>
定义和用法
count_chars() 函数返回字符串中所用字符的信息(例如,ASCII 字符在字符串中出现的次数,或者某个字符是否已经在字符串中使用过)。
语法
count_chars(string,mode)
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
mode |
可选。规定返回模式。默认是 0。以下是不同的返回模式:
|
Technical Details
Return value: | depending on the specified mode Parameters. |
PHP Version: | 4+ |
More Examples
Example 1
Returns a string containing all unused characters in "Hello World!" (pattern 4):
<?php $str = "Hello World!"; echo count_chars($str,4); ?>
Example 2
In this example, we will use count_chars() to check the string, with the return pattern set to 1. Pattern 1 will return an array, with ASCII values as key names and the number of occurrences as key values:
<?php $str = "Hello World!"; print_r(count_chars($str,1)); ?>
Example 3
Another example of counting the number of occurrences of an ASCII character in a string:
<?php $str = "PHP is pretty fun!!"; $strArray = count_chars($str,1); foreach ($strArray as $key=>$value) { echo "Character <b>'".chr($key)."'</b> found $value times.<br>"; } ?>