substr_count()
<?php //Syntax substr_count( string $haystack, string $needle, int $offset = 0, ?int $length = null ): int
The substr_count()
function counts the number of times a substring is found in a string. To use this function, pass the string $haystack
to search and a substring $needle
to search for, see the following example:
<?php $haystack = 'functions are fun'; $needle = 'fun'; $count = substr_count ($haystack, $needle); echo $count; //2
The third argument (optional) is the offset to specify the index position to start searching:
<?php $haystack = 'functions are fun'; $needle = 'fun'; //count in 'ctions are fun' $count = substr_count ($haystack, $needle, 3); echo $count; //1
The fourth argument (optional) is the maximum length the function should search after the offset:
<?php $haystack = 'functions are fun'; $needle = 'fun'; //Counts in 'ctions are fun' echo substr_count($haystack, $needle, 3, 14); //1 //Counts in 'ctions are' echo substr_count($haystack, $needle, 3, 10); //0 //Counts in 'functions ' echo substr_count($haystack, $needle, 0, 10); //1
Note: substr_count()
function generates an error if the sum of offset and length is greater than string $haystack
length. See example:
<?php $haystack = 'functions are fun'; $needle = 'fun'; $hslength = strlen($haystack); //17 // generates an error because 3+15 > 17 echo substr_count($haystack, $needle, 3, 15);
You can use the negative values for the offset and length arguments, if the offset is negative, counting starts from the end of the string. A negative length counts from the end of the $haystack
.
<?php $haystack = 'functions are fun'; $needle = 'fun'; //Counts in 'fun' echo substr_count($haystack, $needle, -3); //1 //Counts in 'ns are ' echo substr_count($haystack, $needle, -10, -3); //0 //Counts in 'function' echo substr_count($haystack, $needle, 0, -9); //1
Note: You can use the substr() function to see the remaining portion of the string $haystack
after providing the offset and length values, for example:
<?php $haystack = 'functions are fun'; $needle = 'fun'; $offset = 0; $length = -9; echo substr ($haystack, $offset, $length); //function echo '<br>'; echo substr_count($haystack, $needle, $offset, $length);//1
mb_substr_count()
mb_substr_count(string $haystack, string $needle, ?string $encoding = null): int
Use this function to count the number of substring occurrences in a multi-byte string:
<?php $haystack = '.цом, .нет, .орг, .нет'; $needle = 'нет'; $encoding = 'UTF-8'; echo mb_substr_count($haystack, $needle); //2 echo mb_substr_count($haystack, $needle, $encoding); //2
Manipulating substrings: