The mb_substr_count Function
The mb_substr_count function returns the number of substring occurrences in a string. Unlike substr_count, it works correctly with multibyte encodings (UTF-8 and others). The first parameter is the string to search in, the second is the substring to find. The third optional parameter specifies the encoding.
Syntax
mb_substr_count(string $haystack, string $needle, ?string $encoding = null): int
Example
Let's count the number of occurrences of the substring 'ab' in the string:
<?php
$res = mb_substr_count('abcdeabab', 'ab');
echo $res;
?>
Code execution result:
3
Example
Counting occurrences with UTF-8 encoding specified:
<?php
$res = mb_substr_count('привет мир', 'ир', 'UTF-8');
echo $res;
?>
Code execution result:
2
Example
Comparison with regular substr_count on Cyrillic text:
<?php
$str = 'тест тест';
echo 'substr_count: ' . substr_count($str, 'те') . '<br>';
echo 'mb_substr_count: ' . mb_substr_count($str, 'те', 'UTF-8');
?>
Code execution result:
'substr_count: 3'
'mb_substr_count: 2'
See Also
-
the
substr_countfunction,
which counts substring occurrences without multibyte encoding support -
the
mb_strposfunction,
which finds the position of the first substring occurrence