php计算子串在字符串中出现次数的函数substr_count()

黄舟
发布: 2017-11-06 13:37:44
原创
2389人浏览过

实例

计算 "world" 在字符串中出现的次数:

<?php
echo substr_count("Hello world. The world is nice","world");
?>
登录后复制

substr_count() 函数计算子串在字符串中出现的次数。

注释:子串是区分大小写的。

注释:该函数不计数重叠的子串(参见实例 2) 。

注释:如果 start 参数加上 length 参数大于字符串长度,该函数则生成一个警告(参见实例 3)。

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

语法

substr_count(string,substring,start,length)
登录后复制
参数 描述
string 必需。规定要检查的字符串。
substring 必需。规定要检索的字符串。
start 可选。规定在字符串中何处开始搜索。
length 可选。规定搜索的长度。

技术细节

返回值: 返回子串在字符串中出现的次数。
PHP 版本: 4+
更新日志 在 PHP 5.1 中,新增了 start 和 length 参数。

更多实例

实例 1

使用所有的参数:

<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
登录后复制

实例 2

重叠的子串:

<?php
$str = "abcabcab"; 
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
登录后复制

实例 3

如果 start 和 length 参数超过字符串长度,该函数则输出一个警告:

<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
登录后复制

由于长度值超过字符串的长度(3 + 9大于12)。所以这将输出一个警告。

举例:

<?php
$text = 'This is a test';
echo strlen($text) . '<br />'; // 输出14
 
echo substr_count($text, 'is') . '<br />'; // 2
 
// the string is reduced to 's is a test', so it prints 1
echo substr_count($text, 'is', 3) . '<br />';//实际上就是从第四个字符开始查找是否在$text中含有is
 
// the text is reduced to 're ', so it prints 0
echo substr_count($text, 'are', 16, 3) . '<br />';
 
// the text is reduced to 's i', so it prints 0echo substr_count($text, 'is', 3, 3);
 
// generates a warning because 5+10 > 14
echo substr_count($text, 'is', 5, 10) . '<br />';
 
 
// prints only 1, because it doesn't count overlapped subtrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd') . '<br />';
 ?>
登录后复制

以上就是php计算子串在字符串中出现次数的函数substr_count()的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

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

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

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