How to calculate how many m characters there are in a string in php

青灯夜游
Release: 2023-03-16 14:10:02
Original
2299 people have browsed it

Two calculation methods: 1. Use the for statement to loop through the characters in the string and count the number of m characters. The syntax "$con=0;for($i=0;$i

How to calculate how many m characters there are in a string in php

The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer

php calculates strings How many m characters are there

Method 1: Use the for statement to loop through the characters in the string and count the number of m characters

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

How to calculate how many m characters there are in a string in php

Method 2: Use the substr_count() function to count the number of m characters

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

How to calculate how many m characters there are in a string in php

Instructions:

substr_count() function counts the number of times a substring appears in a string. (Substrings are case-sensitive.)

substr_count(string,substring,start,length)
Copy after login
Parameter Description
string Required. Specifies the string to check.
substring Required. Specifies the string to be retrieved.
start Optional. Specifies where in the string to begin the search.
length Optional. Specifies the length of the search.

Return value: Returns the number of times the substring appears in the string.

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to calculate how many m characters there are in a string in php. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template