php计算指定字符串出现次数

在做php开发的时候遇到一个问题,想要计算查询指定字符串在原字符串中出现了多少次,那么用php要怎么实现呢?

php计算字符串次数的函数有两个,分别是:

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

mb_substr_count()计算给定字符串中子字符串的总数;

substr_count()统计次数的方法:

substr_count()语法:

substr_count(string,substring,start,length)
参数描述
string必需。规定被检查的字符串。
substring必需。规定要搜索的字符串。
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."次";
?>

输出结果:

php计算指定字符串出现次数  第1张

例子2:

<?php
	header("Content-type:text/html;charset=utf-8");
	$str="我爱上海。上海是中国最大的城市";
	echo "原字符串:".$str."<br>";
	$count=substr_count($str,"上海");
	echo "上海  出现了:".$count."次";
?>

输出结果:

php计算指定字符串出现次数  第2张

mb_substr_count()统计次数的方法:

语法:

mb_substr_count(str $haystack, str $needle, str $encoding)
参数描述
$haystack此参数将检查字符串。
$needle此参数将用于告诉从给定的总字符串中找到子字符串。
$encoding该参数为字符编码。如果它不存在或为空,则将使用内部字符编码值。

例子1:

<?php
	header("Content-type:text/html;charset=utf-8");
	$str="我爱上海。上海是中国最大的城市。";
	echo "原字符串:".$str."<br>";
	$count=mb_substr_count($str,"中国");
	echo "中国 出现了:".$count."次";
?>

输出结果:

php计算指定字符串出现次数  第3张

例子2:

<?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计算指定字符串出现次数  第4张

以上就是关于php怎么计算指定字符串出现次数的详细内容。

本文来源:词雅网

本文地址:https://www.ciyawang.com/php-substr-41.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐