Two methods to query the number of occurrences of a string: 1. Use the substr_count() function to calculate the number of times a specified substring appears in a string in a case-sensitive manner. The syntax "substr_count(string, search sub String, start search position, search length)". 2. Use the mb_substr_count() function to count the number of occurrences of a string. The syntax is "mb_substr_count (string, search substring, character encoding)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
php query string There are two functions for the number of occurrences
substr_count() function
mb_substr_count() function
Method 1: Use the substr_count() function to count the number of times
The substr_count() function counts the number of times a substring appears in a string (case-sensitive).
Syntax:
substr_count(string,substring,start,length)
string Required. Specifies the string to be checked.
#substring Required. Specifies the string to search for.
#start Optional. Specifies where in the string to begin the search.
#length Optional. Specifies the length of the search.
Note: If the start parameter plus the length parameter is greater than the string length, this function generates a warning.
Example 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."次"; ?>
Output result:
<?php header("Content-type:text/html;charset=utf-8"); $str="我爱上海。上海是中国最大的城市"; echo "原字符串:".$str."<br>"; $count=substr_count($str,"上海"); echo "上海 出现了:".$count."次"; ?>
Method 2: Use the mb_substr_count() function to count the number of times
The mb_substr_count() function counts the number of times a string appears. Syntax:mb_substr_count(string,substring,encoding)
<?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 Video Tutorial》
The above is the detailed content of How to query the number of occurrences of a string in php. For more information, please follow other related articles on the PHP Chinese website!