PHP - Finding the Number of Occurrences with substr_count()

Introduction

To find the Number of Occurrences, use substr_count() function.

To use it, pass the string to search and the text to search for, and the function returns the number of times the text was found in the string.

Demo

<?php
    $myString = "this is a test test test!";
    echo substr_count( $myString, "test" ); 
?>/*  w w  w  .  ja va 2s  .c om*/

Result

You can pass an optional third argument to specify the index position to start searching, and an optional fourth argument to indicate how many characters the function should search before giving up.

Here are some examples that use these third and fourth arguments:

Demo

<?php
$myString = "I say, nay, nay, and nay name nay nay!";
echo substr_count( $myString, "nay", 9 ) . " \n ";    
echo substr_count( $myString, "nay", 9, 6 ) . " \n "; 
?>/*from  w  w w .  j a v a 2 s .  c  om*/

Result

Related Topic