Current Location: Home> Function Categories> substr_count

substr_count

Calculate the number of occurrences of substrings
Name:substr_count
Category:String
Programming Language:php
One-line Description:Calculates the number of times a substring appears in a string.

Definition and usage

substr_count() function calculates the number of times a substring appears in a string.

Comment: Substrings are case sensitive.

Note: This function does not count overlapping substrings (see Example 3).

Note: If the start parameter plus length parameter is greater than the string length, the function generates a warning (see Example 4).

Example

Example 1

Calculate the number of times "Shanghai" appears in a string:

 <?php
echo substr_count ( "I love Shanghai. Shanghai is the biggest city in china." , "Shanghai" ) ;
?>

Try it yourself

Example 2

Use all parameters:

 <?php
$str = "This is nice" ;
echo strlen ( $str ) . "<br>" ; // Use strlen() to return the string length
echo substr_count ( $str , "is" ) . "<br>" ; // Number of times "is" appears in the string
echo substr_count ( $str , "is" , 2 ) . "<br>" ; // The string is reduced to "is is nice"
echo substr_count ( $str , "is" , 3 ) . "<br>" ; // The string is reduced to "s is nice"
echo substr_count ( $str , "is" , 3 , 3 ) . "<br>" ; // The string is reduced to "si"
?>

Try it yourself

Example 3

Overlapping substrings:

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

Try it yourself

Example 4

If the start and length parameters exceed the string length, the function outputs 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), a warning is outputted using it.

grammar

 substr_count ( string , substring , start , length )
parameter describe
string Required. Specifies the string to be checked.
Substring Required. Specifies the string to search.
start Optional. Specifies where to start searching in the string.
length Optional. Specify the length of the search.
Similar Functions
  • Convert the first byte of the string to a value between 0-255 ord

    ord

    Convertthefirstbyteo
  • Format a number in a thousand separator number_format

    number_format

    Formatanumberinathou
  • Parse strings into multiple variables parse_str

    parse_str

    Parsestringsintomult
  • Tag split string strtok

    strtok

    Tagsplitstring
  • Write the formatted string to the stream fprintf

    fprintf

    Writetheformattedstr
  • Convert logical-Hebrew to visual-Hebrew and convert newlines hebrevc

    hebrevc

    Convertlogical-Hebre
  • Find the first occurrence of a string strstr

    strstr

    Findthefirstoccurren
  • Convert the first letter of each word in the string to uppercase ucwords

    ucwords

    Convertthefirstlette
Popular Articles