Count the number of occurrences of "world" in a string:
<?phpecho substr_count("Hello world. The world is nice","world");?>The substr_count() function counts the number of times a substring appears in a string.
Note: Substrings are case-sensitive.
Note: This function does not count overlapping substrings (see Example 2).
Note: This function generates a warning if the start parameter plus the length parameter is greater than the string length (see Example 3).
substr_count( string,substring,start,length )
parameter | describe |
---|---|
string | Required. Specifies the string to check. |
substring | Required. Specifies the string to be retrieved. |
start | Optional. Specifies where in the string to begin the search. |
length | Optional. Specifies the length of the search. |
Return value: | Returns the number of times a substring appears in a string. |
---|---|
PHP version: | 4+ |
Update log: | In PHP 5.1, new start and length parameters were added. |
Use all parameters:
<?php$str = "This is nice";echo strlen($str)."<br>"; // Using strlen() to return the string lengthecho substr_count($str,"is")."<br> "; // The number of times "is" occurs in the stringecho substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is PHP"echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"echo substr_count($str,"is",3,3)."<br> "; // The string is now reduced to "si"?>Overlapping substrings:
<?php$str = "abcabcab"; echo substr_count($str,"abcab"); // This function does not count overlapped substrings?>If the start and length parameters exceed the string length, this function outputs a warning:
<?phpecho $str = "This is nice";substr_count($str,"is",3,9);?>Since the length value exceeds the length of the string (3+9 is greater than 12). So this will output a warning.