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

phpmb_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<?php
  $res = mb_substr_count('abcdeabab', 'ab');
  echo $res;
?>

Code execution result:

php3

Example

Counting occurrences with UTF-8 encoding specified:

php<?php
  $res = mb_substr_count('привет мир', 'ир', 'UTF-8');
  echo $res;
?>

Code execution result:

php2

Example

Comparison with regular substr_count on Cyrillic text:

php<?php
  $str = 'тест тест';
  echo 'substr_count: ' . substr_count($str, 'те') . '<br>';
  echo 'mb_substr_count: ' . mb_substr_count($str, 'те', 'UTF-8');
?>

Code execution result:

php'substr_count: 3'
'mb_substr_count: 2'

See Also

  • the substr_count function,
    which counts substring occurrences without multibyte encoding support
  • the mb_strpos function,
    which finds the position of the first substring occurrence