Home >Backend Development >PHP Tutorial >How to count the occurrences of substrings in PHP
PHP method to count the number of occurrences of substrings: first create an HTML sample file; then define 3 string variables; finally use the PHP built-in function substr_count() to find and count the number of occurrences of substrings That’s it.
#The operating environment of this article: Windows 7 system, PHP version 7.1, Dell G3 computer.
In PHP, you can use the built-in function substr_count() to find and count the number of occurrences of substrings. This article will introduce you to the substr_count() function and how to use it. .
PHP substr_count() function
The substr_count() function is used to count the number of occurrences of a substring in a given string.
Basic syntax:
substr_count($str1,$str2,$start,$length);
$str1 Parameter: Indicates the specified string, required parameter.
$str2 parameter: Indicates the substring to be found, required parameter.
$start parameter: Optional parameter, indicating the position in the string to start searching for statistics.
$length parameter: optional parameter, indicating the length of the search.
Note: Substrings are case-sensitive.
Simple example:
[Related video tutorial recommendations: PHP tutorial]
Pass below Simple code example to introduce the use of substr_count() function
Example 1:
<?php $s1 = "PHP中文网-PHP,php,javascript,PHP"; $s2 = "PHP"; $s3 = "php"; $res1 = substr_count($s1, $s2); $res2 = substr_count($s1, $s3); echo("PHP出现的次数:".$res1); echo("<br>"); echo("php出现的次数:".$res2); ?>
Output:
Example 2: If the start and length parameters exceed the string length, the function will output a warning:
<?php header("content-type:text/html;charset=utf-8"); $s1 = "PHP中文网-PHP,php,javascript,PHP"; $s2 = "PHP"; $res = substr_count($s1, $s2,30,10); echo("PHP出现的次数:".$res); ?>
Output:
The above is the entire content of this article, I hope it will be helpful to everyone's study. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to count the occurrences of substrings in PHP. For more information, please follow other related articles on the PHP Chinese website!