Php substr count
From w3cyberlearnings
Contents |
PHP function substr_count
This function counts the number of times substring occurs within the given string.
Syntax substr_count
- string: string input
- substring: string to search for
- start: where to start searching
- length: maximum length of the search
substr_count(string,substring,start,length)
Example 1
<?php echo substr_count("I want to tell her how I feel not to tell her","I"); ?>
Output
2
Example 2: Count whitespace or empty space
<?php echo substr_count("I give you everything!"," "); ?>
Output
3
Example 3
<?php $fruits = array('apple', 'banana', 'orange', 'mango', 'grap'); foreach ($fruits as $f) { if (substr_count($f, 'a') > 2) { echo $f; } } ?>
Output
banana
Example 4
<?php ///////////////////x x x x x x echo substr_count("oh ok, orange color only please", "o"); //6 ///////////////////12345 x x x x echo substr_count("oh ok, orange color only please", "o", 5); //4 ///////////////////12345 1 1 1 1 // no oo occurs within the string echo substr_count("oh ok, orange color only please", "o", 5, 2); //0 ///////////////////123456 x x x x echo substr_count("oh ok, orange color only please", "o", 6); //4 ///////////////////123456 x x x x echo substr_count("oh ok, orange color only please", "o", 6,2); //1 ///////////////////1 x x x x x echo substr_count("oh ok, orange color only please", "o", 1,3); //1 ?>