Home > Article > Backend Development > How to find the number of occurrences of a specified character in a php string
Two ways to find the number of times: 1. Use the substr_count() function to count the number of times English and Chinese characters appear in a string in a case-sensitive manner. The syntax "substr_count(string, specified character, start Search position, search length)". 2. Use the mb_substr_count() function to count the number of times English characters or Chinese characters appear in a string in a case-sensitive manner. The syntax is "mb_substr_count(string, specified character, character encoding)".
The operating environment of this tutorial: windows7 system, PHP version 8.1, DELL G3 computer
How to find specified characters in a php string The number of occurrences? PHP provides two functions to achieve this:
substr_count()
mb_substr_count()
Both functions can count the number of times a substring (English and Chinese characters) appears in a string (case-sensitive); but the mb_substr_count() function can set the character encoding.
Method 1: Use the substr_count() function to find the number of occurrences of a specified character
The substr_count() function counts the number of times English and Chinese characters appear in a string.
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.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $str="16abcdDcbasA76"; echo $str."<br><br>"; $count=substr_count($str,"a"); echo "字符a 出现了:".$count."次"; ?>
Method 2: Use the mb_substr_count() function to find the number of occurrences of a specified character
mb_substr_count() function counts the number of times English and Chinese characters appear in a string (character encoding can be set).
mb_substr_count(string,substring,encoding)
string Required. Specifies the string to be checked.
substring Required. Specifies the string to search for.
encoding Optional. Specifies the character encoding. If omitted or null, the internal character encoding is used.
Example:
<?php header("Content-type:text/html;charset=utf-8"); $str="我爱上海。上海是中国最大的城市。"; echo $str."<br><br>"; $count=mb_substr_count($str,"上海"); echo "上海 出现了:".$count."次"; ?>
<?php header("Content-type:text/html;charset=utf-8"); $str="16abcdDcbasA76"; echo $str."<br><br>"; $count=mb_substr_count($str,"A"); echo "字符A 出现了:".$count."次"; ?>
Recommended learning: "PHP video tutorial 》
The above is the detailed content of How to find the number of occurrences of a specified character in a php string. For more information, please follow other related articles on the PHP Chinese website!