PHP substr_count() 函數(shù)
PHP substr_count() 函數(shù)
實例
計算 "world" 在字符串中出現(xiàn)的次數(shù):
<?php
echo substr_count("Hello world. The world is nice","world");
?>
echo substr_count("Hello world. The world is nice","world");
?>
運行實例 ?
substr_count() 函數(shù)計算子串在字符串中出現(xiàn)的次數(shù)。
注釋:子串是區(qū)分大小寫的。
注釋:該函數(shù)不計數(shù)重疊的子串(參見實例 2) 。
注釋:如果 start 參數(shù)加上 length 參數(shù)大于字符串長度,該函數(shù)則生成一個警告(參見實例 3)。
語法
substr_count(string,substring,start,length)
參數(shù) | 描述 |
---|---|
string | 必需。規(guī)定要檢查的字符串。 |
substring | 必需。規(guī)定要檢索的字符串。 |
start | 可選。規(guī)定在字符串中何處開始搜索。 |
length | 可選。規(guī)定搜索的長度。 |
技術細節(jié)
返回值: | 返回子串在字符串中出現(xiàn)的次數(shù)。 |
---|---|
PHP 版本: | 4+ |
更新日志: | 在 PHP 5.1 中,新增了 start 和 length 參數(shù)。 |
更多實例
實例 1
使用所有的參數(shù):
<?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 參數(shù)超過字符串長度,該函數(shù)則輸出一個警告:
<?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 變量
- PHP 文件處理
- PHP 文件上傳
- PHP array() 函數(shù)
- PHP array_change_key_case() 函數(shù)
- PHP array_key_exists() 函數(shù)
- PHP array_merge_recursive() 函數(shù)
- PHP array_slice() 函數(shù)
- PHP array_walk_recursive() 函數(shù)
- PHP arsort() 函數(shù)
- PHP asort() 函數(shù)
- PHP natsort() 函數(shù)
- PHP next() 函數(shù)
- PHP reset() 函數(shù)
- PHP 5 Directory 函數(shù)
- PHP 5 Filesystem 函數(shù)
- PHP Filter 函數(shù)
- PHP 雜項 函數(shù)
- PHP 5 MySQLi 函數(shù)
- PHP PDO