This question already has an answer here:
I have a string like this:
$str = 'this is a string';
And this is my pattern: /i/g
. There is three occurrence (as you see in the string above, it is containing three i
). Now I need to count that. How can I get that number?
</div>
you can use substr_count() as well as preg_match_all()
echo substr_count("this is a string", "i"); // will echo 3
echo $k_count = preg_match_all('/i/i', 'this is a string', $out); // will echo 3
other method is convert into array and then count it:
$arr = str_split('this is a string');
$counts = array_count_values($arr);
print_r($counts);
output:
Array
(
[t] => 2
[h] => 1
[i] => 3
[s] => 3
[ ] => 3
[a] => 1
[r] => 1
[n] => 1
[g] => 1
)
You should use substr_count().
$str = 'this is a string';
echo substr_count($str, "i"); // 3
You can also use mb_substr_count()
$str = 'this is a string';
echo mb_substr_count($str, "i"); // 3
substr_count — Count the number of substring occurrences
mb_substr_count — Count the number of substring occurrences
preg_match_all could be a better fit.
Here is an example:
<?php
$subject = "a test string a";
$pattern = '/a/i';
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>
Prints:
Array ( [0] => Array ( [0] => a [1] => a ) )