English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
PHP String Manual of String Functions
The substr_count() function is used to count the number of times a substring appears in a string.
substr_count(string,substring,start,length)
substr_count() returns the number of times the substring substring appears in the string string. Note that substring is case-sensitive.
The function returns an integer. It returns the number of times the substring appears in the string.
Number | Parameters and Description |
---|---|
1 | string Specify the string in which to search. |
2 | substring Used to specify the string to be searched |
3 | start It specifies when to start searching in the string, the offset position for counting. If it is negative, it starts counting from the end of the character. |
4 | length It specifies the length of the string |
Try the following example to count the number of occurrences of "krishna" in the string:
<?php //Count the number of occurrences of "krishna" in the string echo substr_count("sairamkrishna","krishna"); echo '<br>'; $text = 'This is a test'; echo strlen($text); // 14 echo '<br>'; echo substr_count($text, 'is'); // 2 echo '<br>'; // The string is simplified to 's is a test', so the output is 1 echo substr_count($text, 'is', 3); echo '<br>'; // The string is simplified to 's i', so the output is 0 echo substr_count($text, 'is', 3, 3); echo '<br>'; // Output 1Because this function does not count overlapping strings $text2 = 'gcdgcdgcd'; echo substr_count($text2, 'gcd'); echo '<br>'; // Because 5+10 > 14Therefore, a warning is generated echo substr_count($text, 'is', 5, 10); ?>Test and see‹/›
Output Result
1 14 2 1 0 3 PHP Warning: Invalid length value in substr_count():...