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
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('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; ?>
Method 2: Use the substr_count() function to count the number of m characters
<?php header('content-type:text/html;charset=utf-8'); $str="m34mvghm45m67mm"; echo "原字符串:".$str."<br>"; echo "m字符的个数:".substr_count($str,"m"); ?>
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)
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!