PHPのsubstr_count()関数
例
「世界」の数をカウントし、文字列に表示されます。
<?php
echo substr_count("Hello world. The world is nice","world");
?>
echo substr_count("Hello world. The world is nice","world");
?>
実行中のインスタンス»
substr_count()関数は、文字列の部分文字列内の出現回数を計算します。
注:サブストリングは、大文字と小文字が区別されます。
注:この関数は、(実施例2参照)重なる部分文字列をカウントしません。
注:引数を開始プラス長さのパラメータは、文字列の長さよりも大きい場合は、警告を生成する関数は、(実施例3を参照)。
文法
substr_count( string,substring,start,length )
参数 | 描述 |
---|---|
string | 必需。规定要检查的字符串。 |
substring | 必需。规定要检索的字符串。 |
start | 可选。规定在字符串中何处开始搜索。 |
length | 可选。规定搜索的长度。 |
技術的詳細
戻り値: | 文字列の部分文字列内の出現回数を返します。 |
---|---|
PHPバージョン: | 4+ |
更新ログ: | 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 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
文字列の長さにわたって開始し、長さのパラメータの場合、この関数は警告を出力します。
<?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の文字列リファレンス