Home>

Substr_count () in PHP can be used to count the number of times a substring appears in a specified string.

The substr_count () function is defined as follows:

substr_count (string, substring, start, length)

Parameter Description:

string Required. Specifies the string to be checked

substring Required. Specifies the string to search.

start Optional. Specifies where to start the search in the string.

length Optional. Specifies the length of the search.

Sample codeThe following:

<?php
 echo substr_count ($str, "script");
 echo "<br />";
 echo substr_count ($str, "script", 16);//Specify that the search starts after the 16th character
 echo "<br />";
 echo substr_count ($str, "script", 16,10);//Specify the search starting from the 16th character and ending with 10 characters
?>

The results are as follows:

3
2
1

parameter description
string essential. Specifies the string to be checked
substring essential. Specifies the string to search.
start Optional. Specifies where to start the search in the string.
length Optional. Specifies the length of the search.

technical details

return value: Returns the number of times a substring appears in a string.
php version: 4+
Update log: In php 5.1, the start and length parameters were added.

More examples

Example 1

Use all parameters:

<?php
$str="this is nice";
echo strlen ($str). "<br>";//use strlen () to return the length of the string
echo substr_count ($str, "is"). "<br>";//the number of times "is" appears in the string
echo substr_count ($str, "is", 2). "<br>";//string is reduced to "is is nice"
echo substr_count ($str, "is", 3). "<br>";//string is reduced to "s is nice"
echo substr_count ($str, "is", 3,3). "<br>";//string is reduced to "s i"
?>

Example 2

Overlapping substrings:

<?php
$str="abcabcab";
echo substr_count ($str, "abcab");//this function does not count overlapping substrings
?>

Example 3

If the start and length parameters exceed the string length,The function will output a warning:

<?php
echo $str="this is nice";
substr_count ($str, "is", 3,9);
?>

Because the length value exceeds the length of the string (3 + 9 is greater than 12), use will output a warning.

php
  • Previous Summary of JS movement-related knowledge points (with elastic movement example)
  • Next jquery limit text box can only enter numbers (integer and decimal)