PHP substr_count() 函式
示例
計算字串中 "world" 出現的次數
<?php
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 | 可選。指定在 string 中開始搜尋的位置。如果為負數,則從字串末尾開始計數 |
length | 可選。指定搜尋的長度 |
技術詳情
返回值 | 返回 substring 在 string 中出現的次數 |
---|---|
PHP 版本 | 4+ |
更新日誌 | PHP 7.1 - length 引數可以是 0 或負數。 PHP 7.1 - start 引數可以是負數。 PHP 5.1 - 添加了 start 和 length 引數。 |
更多示例
示例
使用所有引數
<?php
$str = "This is nice";
echo strlen($str)."<br>"; // 使用 strlen() 返回字串長度
echo substr_count($str,"is")."<br>"; // "is" 在字串中出現的次數
echo substr_count($str,"is",2)."<br>"; // 字串現在縮減為 "is is nice"
echo substr_count($str,"is",3)."<br>"; // 字串現在縮減為 "s is nice"
echo substr_count($str,"is",3,3)."<br>"; // 字串現在縮減為 "s i"
?>
自己動手試一試 »
示例
如果 start 和 length 引數超出字串長度,此函式將輸出警告
<?php
echo $str = "This is nice";
substr_count($str,"is",3,9);
?>
這將輸出警告,因為 length 值超出了字串長度(3+9 大於 12)
❮ PHP 字串參考