array ( 0 => 'index.php', 1 => 'PHP Manual', ), 'head' => array ( 0 => 'UTF-8', 1 => 'ja', ), 'this' => array ( 0 => 'function.substr-count.php', 1 => 'substr_count', ), 'up' => array ( 0 => 'ref.strings.php', 1 => 'String 関数', ), 'prev' => array ( 0 => 'function.substr-compare.php', 1 => 'substr_compare', ), 'next' => array ( 0 => 'function.substr-replace.php', 1 => 'substr_replace', ), 'alternatives' => array ( ), 'source' => array ( 'lang' => 'ja', 'path' => 'reference/strings/functions/substr-count.xml', ), ); $setup["toc"] = $TOC; $setup["toc_deprecated"] = $TOC_DEPRECATED; $setup["parents"] = $PARENTS; manual_setup($setup); ?>
(PHP 4, PHP 5, PHP 7, PHP 8)
substr_count — 副文字列の出現回数を数える
substr_count() は、文字列
haystack
の中での副文字列
needle
の出現回数を返します。
needle
は英大小文字を区別することに注意してください。
注意:
この関数は重なり合う副文字列をカウントしません。以下の例を見てください !
haystack
検索対象の文字列
needle
検索する副文字列
offset
開始位置のオフセット。 負の数を指定すると、文字列の末尾から数えます。
length
指定したオフセット以降に副文字列で検索する最大長。
オフセットと長さの総和が haystack
の長さよりも長い場合、警告が発生します。
負の数を指定すると、haystack
の末尾から数えます。
この関数は 整数を返します。
バージョン | 説明 |
---|---|
8.0.0 |
length は、nullable になりました。
|
7.1.0 |
負の offset と length をサポートするようになりました。
length は、0 を指定しても問題ありません。
|
例1 substr_count() の例
<?php
$text = 'This is a test';
echo strlen($text); // 14
echo substr_count($text, 'is'); // 2
// 文字列は 's is a test' になっているので, 1 が表示される
echo substr_count($text, 'is', 3);
// テキストは 's i' になっているので, 0 が表示される
echo substr_count($text, 'is', 3, 3);
// 5+10 > 14 なので、警告が発生する
echo substr_count($text, 'is', 5, 10);
// 重なっている副文字列はカウントされないので、1 が表示される
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>