substr_count

(PHP 4, PHP 5, PHP 7, PHP 8)

substr_count計算字串出現的次數

說明

substr_count(
    string $haystack,
    string $needle,
    int $offset = 0,
    ?int $length = null
): int

substr_count() 返回子字符串 needle 在字符串 haystack 中出現的次數。注意 needle 區(qū)分大小寫。

注意:

該函數不會計算重疊字符串!參見下面的例子。

參數

haystack

在此字符串中進行搜索。

needle

要搜索的字符串。

offset

開始計數的偏移位置。如果是負數,就從字符的末尾開始統計。

length

指定偏移位置之后的最大搜索長度。如果偏移量加上這個長度的和大于 haystack 的總長度,則打印警告信息。 負數的長度 length 是從 haystack 的末尾開始統計的。

返回值

該函數返回 int。

更新日志

版本 說明
8.0.0 length 可以為空(nullable)。
7.1.0 開始支持負數的 offsetlength。

范例

示例 #1 substr_count() 范例

<?php
$text 
'This is a test';
echo 
strlen($text); // 14

echo substr_count($text'is'); // 2

// 字符串被簡化為 's is a test',因此輸出 1
echo substr_count($text'is'3);

// 字符串被簡化為 's i',所以輸出 0
echo substr_count($text'is'33);

// 因為 5+10 > 14,所以生成警告
echo substr_count($text'is'510);


// 輸出 1,因為該函數不計算重疊字符串
$text2 'gcdgcdgcd';
echo 
substr_count($text2'gcdgcd');
?>

參見