PHP substr_count() 関数

❮ PHP 文字列リファレンス

文字列に "world" が現れる回数を数えます:

<?php
echo substr_count("Hello world. The world is nice","world");
?>
例の実行 »

substr_count() 関数は、文字列に部分文字列が含まれている回数をカウントします。

注: substring は、大文字と小文字が区別されます。

注: この関数は、重複した substring を数えません(例 2 を参照)。

注: このファンクションは、start パラメータと length パラメータを加えた値が、 文字列の長さを超えた場合は警告が発生します(例 3 を参照)。


構文

substr_count(string,substring,start,length)

パラメータ 説明
string 必須。チェックする文字列を指定する
substring 必須。検索する文字を指定する
start 任意。文字列の開始位置を指定する searching
length 任意。検索する長さを指定する

技術内容
返り値: 文字列に substring が含まれる回数を返します
PHP バージョン: 4+
変更歴 startlength パラメータは PHP 5.1 で追加されました

その他の例

例 1

すべてのパラメータを使用する:

<?php
$str = "This is nice";
echo strlen($str)."<br>"; // Using strlen() to return the string length
echo substr_count($str,"is")."<br>"; // The number of times "is" occurs in the string
echo substr_count($str,"is",2)."<br>"; // The string is now reduced to "is is nice"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
例の実行 »

例 2

部分文字列の重複:

<?php
$str = "abcabcab";
echo substr_count($str,"abcab"); // This function does not count overlapped substrings
?>
例の実行 »

例 3

startとlengthパラメータが文字列の長さを超えた場合、この関数は警告を発します:

<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>

This will output a warning because the length value exceeds the string length (3+9 is greater than 12)


❮ PHP 文字列リファレンス