兩種查詢字符串出現次數的方法:1、使用substr_count()函數,可區分大小寫的計算指定子串在字符串中出現的次數,語法“substr_count(字符串,搜索子串,開始搜索位置,搜索長度)”。2、使用mb_substr_count()函數,可統計字符串出現的次數,語法“mb_substr_count(字符串,搜索子串,字符編碼)”。
本教程操作環境:windows7系統、PHP8.1版、DELL G3電腦
php查詢字符串出現次數有兩個函數
-
substr_count()函數
-
mb_substr_count()函數
方法1:使用substr_count()函數統計次數
substr_count() 函數計算子串在字符串中出現的次數(區分大小寫的)。
語法:
substr_count(string,substring,start,length)
-
string 必需。規定被檢查的字符串。
-
substring 必需。規定要搜索的字符串。
-
start 可選。規定在字符串中何處開始搜索。
-
length 可選。規定搜索的長度。
注:如果 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."次"; ?>
輸出結果:
示例2:
<?php header("Content-type:text/html;charset=utf-8"); $str="我愛上海。上海是中國最大的城市"; echo "原字符串:".$str."<br>"; $count=substr_count($str,"上海"); echo "上海 出現了:".$count."次"; ?>
方法2:使用mb_substr_count()函數統計次數
mb_substr_count()函數統計字符串出現的次數。
語法:
mb_substr_count(string,substring,encoding)
-
string 必需。規定被檢查的字符串。
-
substring 必需。規定要搜索的字符串。
-
encoding 可選。規定字符編碼。如果省略或是 null,則使用內部字符編碼。
<?php header("Content-type:text/html;charset=utf-8"); $str="我愛上海。上海是中國最大的城市。"; echo "原字符串:".$str."<br>"; $count=mb_substr_count($str,"中國"); echo "中國 出現了:".$count."次"; ?>
輸出結果:
<?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視頻教程》