PHP | Find the number of sub-string occurrences
We are given two strings s1 and s2. We need to find the number of occurrences of s2 in s1.
Examples:
Input : $s1 = "geeksforgeeks", $s2 = "geeks"
Output : 2
Explanation : s2 appears 2 times in s1
Input : $s1 = "Hello Shubham. how are you?";
$s2 = "shubham"
Output : 0
Explanation : Note the first letter of s2
is different from substrings present in s1.
The problem can be solved using PHP in built function for counting the number of occurrences of a substring in a given string.The in built function used for the given problem is:
- substr_count(): The substr_count() function counts the number of times a substring occurs in a string.
Note: The substring is case-sensitive.
<?php // PHP program to count number of times // a s2 appears in s1. $s1 = "geeksforgeeks"; $s2 = "geeks"; $res = substr_count($s1, $s2); echo($res); ?> |
chevron_right
filter_none
Output :
2
Recommended Posts:
- Removing occurrences of a specific character from end of a string in PHP
- PHP to check substring in a string
- Difference between substr() and substring() in JavaScript
- How to check a string is entirely made up of the same substring in JavaScript ?
- Program to find the number of days between two dates in PHP
- JavaScript | Difference between String.slice and String.substring
- How to disable scroll to change number in <input type="number"> field using JavaScript/jQuery?
- PHP | Check if a number is armstrong number
- PHP | Check if a number is Perfect number
- PHP | Ds\Deque find() Function
- PHP | Find Intersection of two arrays
- How to find where the URL will redirected using cURL?
- PHP | Ds\Vector find() Function
- PHP | Ds\Sequence find() Function
- How to find out which character key is pressed using JavaScript?
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



