兩種計算方法: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; ?>
方法2:利用substr_count()函數統計m字符的個數
<?php header('content-type:text/html;charset=utf-8'); $str="m34mvghm45m67mm"; echo "原字符串:".$str."<br>"; echo "m字符的個數:".substr_count($str,"m"); ?>
說明:
substr_count() 函數計算子串在字符串中出現的次數。(子串是區分大小寫的。)
substr_count(string,substring,start,length)
參數 | 描述 |
---|---|
string | 必需。規定要檢查的字符串。 |
substring | 必需。規定要檢索的字符串。 |
start | 可選。規定在字符串中何處開始搜索。 |
length | 可選。規定搜索的長度。 |
返回值:返回子串在字符串中出現的次數。
推薦學習:《PHP視頻教程》