関数 mb_substr_count

関数 mb_substr_count は、文字列内の部分文字列の出現回数を返します。substr_count とは異なり、マルチバイトエンコーディング (UTF-8 など) を正しく処理します。最初のパラメータは検索対象の文字列、2番目は検索する部分文字列を渡します。3番目のオプションパラメータはエンコーディングを指定します。

構文

phpmb_substr_count(string $haystack, string $needle, ?string $encoding = null): int

例

文字列内の部分文字列 'ab' の出現回数をカウントします:

php<?php
  $res = mb_substr_count('abcdeabab', 'ab');
  echo $res;
?>

コードの実行結果:

php3

例

UTF-8 エンコーディングを指定した出現回数のカウント:

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

コードの実行結果:

php2

例

キリル文字での通常の substr_count との比較:

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

コードの実行結果:

php'substr_count: 3'
'mb_substr_count: 2'

関連項目

  • 関数 substr_count,
    マルチバイトエンコーディングをサポートせずに部分文字列の出現回数をカウントします
  • 関数 mb_strpos,
    部分文字列が最初に出現する位置を検索します