php怎么查找字符串出现几次

2021-11-18,

查找方法:1、使用substr_count(),语法“substr_count(string,substring)”;2、使用mb_substr_count(),语法“mb_substr_count(string,substring)”。

/2021/11/376d81ea.jpg

本教程操作环境:windows7系统、PHP7.1版、DELL G3电脑

php查找字符串出现几次

方法1:使用substr_count()函数

substr_count() 函数计算子串在字符串中出现的次数(区分大小写的)。

语法:

substr_count(string,substring,start,length)
  • string 必需。规定被检查的字符串。

  • substring 必需。规定要搜索的字符串。

  • start 可选。规定在字符串中何处开始搜索。

  • length 可选。规定搜索的长度。

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

示例:

<?php
header("Content-type:text/html;charset=utf-8");
$str="I love Shanghai. Shanghai is the biggest city in china.";
$count=substr_count($str,"Shanghai");
echo "Shanghai 出现了:".$count."次";
?>

输出结果:

/2021/11/8737bca0.png" /2021/11/8737bca0.png" alt="1.png

方法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="我爱上海。上海是中国最大的城市。";
$count=mb_substr_count($str,"上海");
echo "上海 出现了:".$count."次";
?>

输出结果:

/2021/11/4d1c7b25.png" /2021/11/4d1c7b25.png" alt="3.png

推荐学习:《PHP视频教程》

以上就是php怎么查找字符串出现几次的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《php怎么查找字符串出现几次.doc》

下载本文的Word格式文档,以方便收藏与打印。