| 參數 | 說明 |
$haystack | 被搜尋字串 |
$needle | 搜尋目標(字串或 ASCII 碼整數) |
$before_needle | true 回傳 $needle 前的部分(PHP 5.3+) |
回傳從 $needle 首次出現位置開始(含本身)到字串結尾的子字串;找不到回傳 false。
基本範例
echo strstr("歡迎來到腳本之家", "腳本"); // 腳本之家
echo strstr("Welcome To www.jb51.net", "jb51"); // jb51.net
echo strstr("123456789", "5"); // 56789
// PHP 5.3+ 取得前段
echo strstr("123456789", "5", true); // 1234
常見應用場景
1. 解析網域/主機名
$url = "https://www.example.com/path?query=1";
$host = strstr($url, '://'); // https://www.example.com/path?query=1
$host = strstr($host, '://', true); // https
// 更穩健請用 parse_url()
2. 截取副檔名
$filename = "document.report.pdf";
$ext = strstr($filename, '.'); // .pdf
// 建議用 pathinfo($filename, PATHINFO_EXTENSION)
3. 簡易模板引擎:提取區塊
$tpl = "[HEADER]...[CONTENT]...[FOOTER]";
$content = strstr($tpl, '[CONTENT]');
$content = strstr($content, '[FOOTER]', true); // [CONTENT]...
效能與替代方案
| 函式 | 用途 | 速度 | 備註 |
strstr | 單一字串搜尋 | 快 | C 實作,二進位安全 |
strpos + substr | 需精確位置控制 | 略快 | 避免建立中間字串 |
preg_match | 複雜模式 | 慢 | 過度殺傷 |
mb_strstr | 多位元組編碼 | 中等 | UTF-8 環境建議使用 |
最佳實務
- 只需判斷是否包含 → 用
strpos($haystack, $needle) !== false,不建立子字串。
- 需取得後段內容 →
strstr 最簡潔。
- 處理 UTF-8 中文 → 改用
mb_strstr,避免截斷多位元組字元。
$needle 為整數時視為 ASCII 碼,較少用,注意別誤傳數值型態。
相關函式速查
stristr:不區分大小寫版本。
strrchr:尋找字元最後一次出現位置並回傳後段。
strchr:strstr 別名。
- 上一篇文章: PHP substr_count() 函式:計算子字串出現次數完整指南
- 下一篇文章: WordPress wp_title() 函式深度解析:動態頁面標題生成指南
Copyright ©
程式碼之家 All Rights Reserved