php计算子串在字符串中出现次数的函数substr_count()
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了php计算子串在字符串中出现次数的函数substr_count(),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2162字,纯文字阅读大概需要4分钟。
内容图文
![php计算子串在字符串中出现次数的函数substr_count()](/upload/InfoBanner/zyjiaocheng/142/fd73e41895bf49e48e79af7facd2ead6.jpg)
实例
计算 "world" 在字符串中出现的次数:
<?php echo substr_count("Hello world. The world is nice","world"); ?>
substr_count() 函数计算子串在字符串中出现的次数。
注释:子串是区分大小写的。
注释:该函数不计数重叠的子串(参见实例 2) 。
注释:如果 start 参数加上 length 参数大于字符串长度,该函数则生成一个警告(参见实例 3)。
语法
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()的详细内容,更多请关注Gxl网其它相关文章!
内容总结
以上是互联网集市为您收集整理的php计算子串在字符串中出现次数的函数substr_count()全部内容,希望文章能够帮你解决php计算子串在字符串中出现次数的函数substr_count()所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。