php返回字符串所有信息的函数count_chars()

黄舟
发布: 2017-11-02 10:20:10
原创
1915人浏览过

实例

返回一个字符串,包含所有在 "hello world!" 中使用过的不同字符(模式 3):

<?php
$str = "Hello World!";
echo count_chars($str,3);
?>
登录后复制

定义和用法

count_chars() 函数返回字符串所用字符的信息(例如,ASCII 字符在字符串中出现的次数,或者某个字符是否已经在字符串中使用过)。

语法

count_chars(string,mode)
登录后复制

参数                       描述

string                     必需。规定要检查的字符串。    

mode                      可选。规定返回模式。默认是 0。有以下不同的返回模式:

立即学习PHP免费学习笔记(深入)”;

                               0 - 数组,ASCII 值为键名,出现的次数为键值

                               1 - 数组,ASCII 值为键名,出现的次数为键值,只列出出现次数大于 0 的值

                               2 - 数组,ASCII 值为键名,出现的次数为键值,只列出出现次数等于 0 的值

                               3 - 字符串,带有所有使用过的不同的字符

怪兽AI数字人
怪兽AI数字人

数字人短视频创作,数字人直播,实时驱动数字人

怪兽AI数字人 44
查看详情 怪兽AI数字人

                               4 - 字符串,带有所有未使用过的不同的字符

技术细节

返回值:       取决于指定的 mode 参数。    

PHP 版本:   4+    

更多实例

实例 1

返回一个字符串,包含所有在 "Hello World!" 中未使用过的字符(模式 4):

<?php
$str = "Hello World!";
echo count_chars($str,4);
?>
登录后复制

实例 2

在本实例中,我们将使用 count_chars() 来检查字符串,返回模式设置为 1。模式 1 将返回一个数组,ASCII 值为键名,出现的次数为键值:

<?php
$str = "Hello World!";
print_r(count_chars($str,1));
?>
登录后复制

实例 3

统计 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>";
}
?>
登录后复制

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.<br/>" ;
}
?>
登录后复制

运行结果:

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返回字符串所有信息的函数count_chars()的详细内容,更多请关注php中文网其它相关文章!

相关标签:
php
PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号