两种计算方法:1、使用for语句循环遍历字符串中的字符,统计m字符的个数,语法“$con=0;for($i=0;$i<strlen($str);$i++){if($str[$i]==="m"){$con++;}}”。2、利用substr_count()函数统计m字符的个数,语法“substr_count($str,"m")”。

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

php计算字符串有多少个m字符的方法

方法1:使用for语句循环遍历字符串中的字符,统计m字符的个数

<?php
header('content-type:text/html;charset=utf-8');   
$str="34mvghm45m67m";
echo "原字符串:".$str."<br>";
$con=0;
for($i=0;$i<strlen($str);$i++){
	if($str[$i]==="m"){
		$con++;
	}
}
echo "m字符的个数:".$con;
?>

1.png

方法2:利用substr_count()函数统计m字符的个数

<?php
header('content-type:text/html;charset=utf-8');   
$str="m34mvghm45m67mm";
echo "原字符串:".$str."<br>";
echo "m字符的个数:".substr_count($str,"m");
?>

2.png

说明:

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

substr_count(string,substring,start,length)
参数描述
string必需。规定要检查的字符串。
substring必需。规定要检索的字符串。
start可选。规定在字符串中何处开始搜索。
length可选。规定搜索的长度。

返回值:返回子串在字符串中出现的次数。


php怎么计算字符串有多少个m字符