首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 字串出現次數統計:substr_count() 與相關搜尋函式全解析

     編輯:PHP 相關知識

核心函式:substr_count()

int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
  • $haystack:母字串
  • $needle:要搜尋的子字串
  • $offset:起始位移(可選)
  • $length:搜尋長度(可選)

實戰範例

$str = "this is a test";
echo substr_count($str, 'is');       // 2
echo substr_count($str, 'is', 3);    // 1 (從第 3 字元開始)
echo substr_count($str, 'is', 3, 3); // 0 (從第 3 字元起長度 3)

$str2 = 'https://www.bkjia.com 愛程序網_軟件編程入門教程_軟件設計交流_字符出現次數';
echo substr_count($str2, 'w');       // 3
echo substr_count($str2, 't');       // 2
echo substr_count($str2, '愛程序網'); // 1

常用字串搜尋函式對照表

函式說明大小寫敏感
strstr尋找首次出現位置,回傳子字串是
stristrstrstr 不分大小寫版本否
strpos尋找首次出現位置(整數索引)是
striposstrpos 不分大小寫版本否
strrpos尋找最後一次出現位置是
strriposstrrpos 不分大小寫版本否
strrchr尋找字元最後一次出現,回傳子字串是
substr擷取子字串—

效能提示

  • 單純計數用 substr_count 最快;
  • 需位置資訊用 strpos/stripos;
  • 大字串頻繁搜尋考慮建立索引或使用全文搜尋引擎。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved