執行個體
計算 "world" 在字串中出現的次數:
<?phpecho substr_count("Hello world. The world is nice","world");?>
substr_count() Function Compute子串在字串中出現的次數。
注釋:子串是區分大小寫。
注釋:該函數不計數重疊的子串(參見執行個體 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 lengthecho substr_count($str,"is")."<br>"; // The number of times "is" occurs in the stringecho 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?>
執行個體 3
如果 start 和 length 參數超過字串長度,該函數則輸出一個警告:
<?phpecho $str = "This is nice";substr_count($str,"is",3,9);?>
由於長度值超過字串的長度(3 + 9大於12)。所以這將輸出一個警告。
舉例:
<?php$text = 'This is a test';echo strlen($text) . '<br />'; // 輸出14 echo substr_count($text, 'is') . '<br />'; // 2 // the string is reduced to 's is a test', so it prints 1echo substr_count($text, 'is', 3) . '<br />';//實際上就是從第四個字元開始尋找是否在$text中含有is // the text is reduced to 're ', so it prints 0echo substr_count($text, 'are', 16, 3) . '<br />'; // the text is reduced to 's i', so it prints 0echo substr_count($text, 'is', 3, 3); // generates a warning because 5+10 > 14echo substr_count($text, 'is', 5, 10) . '<br />'; // prints only 1, because it doesn't count overlapped subtrings$text2 = 'gcdgcdgcd';echo substr_count($text2, 'gcdgcd') . '<br />'; ?>