In this PHP tutorial, you shall learn how to count occurrences of a specific substring in a given string using substr_count() function, with example programs.

PHP – Count Occurrences of Substring in String

To count occurrences of Substring in String, use PHP built-in substr_count() function.

substr_count($str, $substring) function returns the number of non-overlapped occurrences of $substring in the given string $str.

Examples

1. Count occurrences of “Apple” in a string

In this example, we will take a string, and a substring. Then we will call subst_count() function with string and substring as arguments.

PHP Program

<?php
$str = "Apple is happy. Some Apples are red in color.";
$substring = "Apple";
$count = substr_count($str, $substring);
echo $count;
?>

Output

PHP - Count Occurrences of Substring in String

Conclusion

In this PHP Tutorial, we learned how to use substr_count() built-in PHP function to count the number of occurrences of substring in a string.