这篇文章主要介绍了php如何查询字符串出现的次数的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇php如何查询字符串出现的次数文章都会有所收获,下面我们一起来看看吧。
两种查询字符串出现次数的方法:1、使用substr_count()函数,可区分大小写的计算指定子串在字符串中出现的次数,语法“substr_count(字符串,搜索子串,开始搜索位置,搜索长度)”。2、使用mb_substr_count()函数,可统计字符串出现的次数,语法“mb_substr_count(字符串,搜索子串,字符编码)”。

本教程操作环境:windows7系统、PHP8.1版、DELL G3电脑
php查询字符串出现次数有两个函数
substr_count()函数
mb_substr_count()函数
方法1:使用substr_count()函数统计次数
substr_count() 函数计算子串在字符串中出现的次数(区分大小写的)。
语法:
substr_count(string,substring,start,length)
string 必需。规定被检查的字符串。
substring 必需。规定要搜索的字符串。
start 可选。规定在字符串中何处开始搜索。
length 可选。规定搜索的长度。
注:如果 start 参数加上 length 参数大于字符串长度,则该函数生成一个警告。
示例1:
<?php
header("Content-type:text/html;charset=utf-8");
$str="I love Shanghai. Shanghai is the biggest city in china.";
echo "原字符串:".$str."<br>";
$count=substr_count($str,"Shanghai");
echo "Shanghai 出现了:".$count."次";
?>输出结果:

示例2:
<?php
header("Content-type:text/html;charset=utf-8");
$str="我爱上海。上海是中国最大的城市";
echo "原字符串:".$str."<br>";
$count=substr_count($str,"上海");
echo "上海 出现了:".$count."次";
?>
方法2:使用mb_substr_count()函数统计次数
mb_substr_count()函数统计字符串出现的次数。
语法:
mb_substr_count(string,substring,encoding)
string 必需。规定被检查的字符串。
substring 必需。规定要搜索的字符串。
encoding 可选。规定字符编码。如果省略或是 null,则使用内部字符编码。
<?php
header("Content-type:text/html;charset=utf-8");
$str="我爱上海。上海是中国最大的城市。";
echo "原字符串:".$str."<br>";
$count=mb_substr_count($str,"中国");
echo "中国 出现了:".$count."次";
?>输出结果:

<?php
header("Content-type:text/html;charset=utf-8");
$str="I love Shanghai. Shanghai is the biggest city in china.";
echo "原字符串:".$str."<br>";
$count1=mb_substr_count($str,"Shanghai");
echo "Shanghai 出现了:".$count1."次<br>";
$count2=mb_substr_count($str,"shanghai");
echo "shanghai 出现了:".$count2."次";
?>
关于“php如何查询字符串出现的次数”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“php如何查询字符串出现的次数”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注恰卡网行业资讯频道。