Introduction to substr_count in PHP (use range: PhP4 and PhP5)
Let's take a look at the Chinese version of the official explanation:
Purpose: count the number of times that "substring" appears in "original string"
Syntax: int substr_count (string haystack, string needle [, int offset [, int length])
Return Value: Type: integer. Return the number of times the needle sub-string appears in the haystack parent string. The needle string is case sensitive)
Parameters:
Haystack: Search for the parent string
Needle: The substring searched in the parent string.
Offset: the offset of the Start count.
Length: searches for the maximum length of the substring after the specified offset. If the sum of offset and length is greater than the length of the parent string, a warning is output.
The offset and length parameters have been introduced since php5.1.0.
Note: Do not count the parts where the string exceeds the parent string
Example:
<? PHP
$ Text = 'this is a test ';
Echo strlen ($ text). '<br/>'; // output 14
Echo substr_count ($ text, 'is ').' <br/> '; // 2
// The string is already CED to's is a test ', so it prints 1
Echo substr_count ($ text, 'is ', 3).' <br/> '; // The fourth character is used to check whether $ text contains is
// The text is already CED to 'Re', so it prints 0
Echo substr_count ($ text, 'are', 16, 3). '<br/> ';
// The text is already CED to's I ', so it prints
0
Echo substr_count ($ text,
'Is ', 3, 3 );
// Generates a warning because 5 + 10> 14
Echo substr_count ($ text, 'is ', 5, 10).' <br/> ';
// Prints only 1, because it doesn't count overlapped subtrings
$ Text2 = 'gcdgcdgcd ';
Echo substr_count ($ text2, 'gcdgcd'). '<br/> ';
?>
Through the above, we can have a general understanding of this function. Here are two specific applications. (All from the Network)
Application 1:
To calculate the number of replies to a Tianya post, you can calculate the number
Number of times, this function substr_count () can be done.
Application 2:
The substr_count () function is the number of times a small string appears in a large string:
$ Number = substr_count (big_string, small_string );
Today, we need a function for searching strings. To determine whether the string big_string contains the string small_string, return true or fasle;
After checking the manual for half a day, no ready-made functions were found. Therefore, we thought we could use the substr_count function to implement the Code as follows:
Function check_str ($ STR, $ substr)
{
$ Nums = substr_count ($ STR, $ substr );
If ($ Nums> = 1)
{
Return true;
}
Else
{
Return false;
}
}
Super simple!