萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP substr_count() 統計字串中字元出現次數

函數語法

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%
?>
copyright © 萬盛學電腦網 all rights reserved