您的位置:首页 > 编程语言 > PHP开发

浅析php中的substr_count()函数的使用

2010-04-01 13:41 357 查看
php中的substr_count使用介绍 (使用范围PHP4,PHP5)



先来看下官方的解释的中文版:

作用:统计“子字符串”在“原始字符串中出现的次数”

语法:int substr_count(string haystack, string needle [, int offset [,int length]])

返回值:类型:integer.返回needle子字符串在haystack母字符串中出现的次数,其中needle字符串是区分大小写的(大小写敏感)

参数:

haystack:搜索母字符串

needle:在母串中搜索的子字符串

offset:开始统计次数的偏移量

length:在指定的offset偏移量后面搜索子串的最大长度。如偏移量与length之和大于母串长度,则输出警告。

自PHP5.1.0版本开始引入offset,length参数

注意:不统计字串超出母串的部分





举例:

<?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
0
echo 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 />';

?>



通过上面的就可以对这个函数有一个整体的认识了。下面来说两个具体的应用吧。(均来自网络上)

应用1:

想统计一下tianya帖子的回复数,就想统计一下一段字符中某段字符出现的

次数,这个函数substr_count()就可以搞定了。



应用2:

substr_count()函数本是一个小字符串在一个大字符串中出现的次数:

$number = substr_count(big_string, small_string);

正好今天需要一个查找字符串的函数,要实现判断字符串big_string是否包含字符串small_string,返回true或fasle;

查了半天手册没有找到现成的函数,于是想到可以用substr_count函数来实现代码如下:

function check_str($str, $substr)

{

$nums=substr_count($str,$substr);

if ($nums>=1)

{

return true;

}

else

{

return false;

}

}



超级简单!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: