查找方法:1、使用substr_count(),語法“substr_count(string,substring)”;2、使用mb_substr_count(),語法“mb_substr_count(string,substring)”。
本教程操作環境:windows7系統、PHP7.1版、DELL G3電腦
php查找字符串出現幾次
方法1:使用substr_count()函數
substr_count() 函數計算子串在字符串中出現的次數(區分大小寫的)。
語法:
substr_count(string,substring,start,length)
-
string 必需。規定被檢查的字符串。
-
substring 必需。規定要搜索的字符串。
-
start 可選。規定在字符串中何處開始搜索。
-
length 可選。規定搜索的長度。
注:如果 start 參數加上 length 參數大于字符串長度,則該函數生成一個警告。
示例:
<?php header("Content-type:text/html;charset=utf-8"); $str="I love Shanghai. Shanghai is the biggest city in china."; $count=substr_count($str,"Shanghai"); echo "Shanghai 出現了:".$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="我愛上海。上海是中國最大的城市。"; $count=mb_substr_count($str,"上海"); echo "上海 出現了:".$count."次"; ?>
輸出結果:
推薦學習:《PHP視頻教程》