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 inbuilt 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);
?>
Output :
2Using preg_match_all() Function
The preg_match_all() function searches a string for all matches to a given pattern and returns the number of matches.
Example
<?php
function countOccurrences($s1, $s2) {
// Escape special characters in $s2 to safely use it in a regex pattern
$pattern = '/' . preg_quote($s2, '/') . '/';
// Perform a global regular expression match
preg_match_all($pattern, $s1, $matches);
// Return the number of matches found
return count($matches[0]);
}
$s1 = "geeksforgeeks";
$s2 = "geeks";
echo "Number of occurrences of '$s2' in '$s1': " . countOccurrences($s1, $s2) . PHP_EOL;
$s1 = "Hello Shubham. how are you?";
$s2 = "shubham";
echo "Number of occurrences of '$s2' in '$s1': " . countOccurrences($s1, $s2) . PHP_EOL;
?>
Output:
Number of occurrences of 'geeks' in 'geeksforgeeks': 2
Number of occurrences of 'shubham' in 'Hello Shubham. how are you?': 0