Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Count the number of occurrences of a charcter or a substring in a string

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 148
    Comment on it

    This article defines a function substr_count() which can be used for count the occurrences of a character or substring in a string. In general way, substr_count() takes two arguments, first argument is a string and second argument is a character or a string which is to be search inside first argument. The function returns an integer value which defines the number of occurrences of substring found in the string.


    Syntax : substr_count(string, search_string, start_index, length)


    string : The main string to check for occurrences of search_string.(Required)
    search_string : A character or a substring to search in string.(Required)
    start_index : Specify the index for start searching.(Optional)
    length : Defines the search length start from start_index.(Optional)


    Note :

    • The two optional parameters are added from PHP version 5.1.0
    • If the length (start_index + length) is greater than the string of string, The function generates a warning.
    • The search_string is case-sensitive.

    Example 1 :

    <?php
     $str = "This is a testing string";
     echo substr_count($str, 'i');
     echo "<br>";
     echo substr_count($str, 'is');
     echo "<br>";
     echo substr_count($str, 'is', 3, 8);
    ?>
    

    Output : 4
    2
    1


    Example 2 : substr_count() does not count overlapped substrings.

    <?php
     $str = "abcabcabb";
     echo substr_count($str, 'abca');
    ?>
    

    Output : 1


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: