int substr_count(string $haystack, string $needle [, int $offset = 0 [, int $length ]])
$haystack:被搜尋的字串(必填)。$needle:要尋找的子字串(必填)。$offset:起始搜尋位置(選填,預設 0)。$length:搜尋長度(選填,預設到字串結尾)。回傳 $needle 在 $haystack 中出現的次數(不重疊計算)。
<?php
echo substr_count("零的PHP自學手冊", "的"); // 1
echo "<br>";
echo substr_count("www.111cn.net", "o"); // 2
echo "<br>";
echo substr_count("1033114118", "1"); // 5
?>
<?php
$text = "abcdefghijklmnopqrstuvwxyz";
// 從第 5 個字元開始,搜尋長度 10
echo substr_count($text, "c", 5, 10); // 0(範圍內無 c)
echo substr_count($text, "f", 5, 10); // 1(f 在索引 5)
?>
substr_count("ABC", "a") 回傳 0。preg_match_all()。$offset 或 $length 為負數時行為未定義(建議避免)。<?php
function keywordDensity($content, $keyword) {
$totalWords = str_word_count($content);
$keywordCount = substr_count(strtolower($content), strtolower($keyword));
return $totalWords > 0 ? round(($keywordCount / $totalWords) * 100, 2) : 0;
}
$article = "PHP 是一種流行的伺服器端腳本語言。PHP 易學易用。";
echo keywordDensity($article, "PHP"); // 3.23%
?>