PHP substr_count()関数
例
文字列内で "world" が出現する回数を計算する:
<?php
echo substr_count("Hello world. The world is nice","world");
?>
echo substr_count("Hello world. The world is nice","world");
?>
例を実行 »
substr_count() 関数は、文字列内での部分文字列の出現回数を計算します。
注:部分文字列は大文字と小文字を区別します。
注:この関数は重複する部分文字列をカウントしません(例 2 を参照)。
注:start パラメータと length パラメータの合計が文字列の長さより大きい場合、この関数は警告を生成します(例 3 を参照)。
構文
substr_count(string,substring,start,length)
| パラメータ | 説明 |
|---|---|
| string | 必須。チェックする文字列を指定します。 |
| substring | 必須。検索する文字列を指定します。 |
| start | オプション。文字列内で検索を開始する位置を指定します。 |
| length | オプション。検索の長さを指定します。 |
技術詳細
| 戻り値: | 文字列内での部分文字列の出現回数を返します。 |
|---|---|
| PHP バージョン: | 4+ |
| 変更履歴: | PHP 5.1 で、startとlengthパラメータが追加されました。 |
その他の例
例 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 PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
echo substr_count($str,"is",3,3)."<br>"; // The string is now reduced to "s i"
?>
$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 PHP"
echo substr_count($str,"is",3)."<br>"; // The string is now reduced to "s is PHP"
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
?>
$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);
?>
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
長さの値が文字列の長さを超えているため(3 + 9 は 12 より大きい)、警告が出力されます。
PHP String リファレンスマニュアル その他の拡張