首页 >后端开发 >php教程 > 正文

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

原创2017-11-06 13:37:440849

实例

计算 "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()的详细内容,更多请关注php中文网其它相关文章!

php中文网最新课程二维码

声明:本文原创发布php中文网,转载请注明出处,感谢您的尊重!如有疑问,请联系admin@php.cn处理

  • 相关标签:php 字符串 串在
  • 相关文章

    相关视频


    网友评论

    文明上网理性发言,请遵守 新闻评论服务协议

    我要评论
  • 专题推荐

    作者信息

    黄舟

    人生最曼妙的风景,竟是内心的淡定与从容!

    最近文章
    php实现字符串匹配算法之sunday算法的示例3303
    css中关于hideFocus的使用详解3349
    JavaScript中filter函数的详细介绍3122
    推荐视频教程
  • javascript初级视频教程javascript初级视频教程
  • jquery 基础视频教程jquery 基础视频教程
  • 视频教程分类