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參考手冊