Search method: 1. Use substr_count(), syntax "substr_count(string,substring)"; 2. Use mb_substr_count(), syntax "mb_substr_count(string,substring)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php search string How many times does it appear
Method 1: Use the substr_count() function
substr_count() function to count 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:
<?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."次"; ?>
Output result:
##Method 2: Use mb_substr_count() function
mb_substr_count() function counts the number of occurrences of a string. Syntax:mb_substr_count(string,substring,encoding)
<?php header("Content-type:text/html;charset=utf-8"); $str="我爱上海。上海是中国最大的城市。"; $count=mb_substr_count($str,"上海"); echo "上海 出现了:".$count."次"; ?>
PHP Video Tutorial"
The above is the detailed content of How to find how many times a string appears in php. For more information, please follow other related articles on the PHP Chinese website!