搜索表單
<form name="form1" method="post" action="search.php">
<input type="text" name="keyword">
<input type="submit" name="Submit" value="搜索">
</form>
核心搜索邏輯
<?php
set_time_limit(600); // 防止大量文件超時
$keyword = trim($_POST['keyword'] ?? '');
if (!$keyword) { echo "關鍵字不能為空"; exit; }
$results = [];
function listFiles($dir, $keyword, &$results) {
$handle = opendir($dir);
while (false !== ($file = readdir($handle))) {
if ($file === '.' || $file === '..') continue;
$path = "$dir/$file";
if (is_dir($path)) {
listFiles($path, $keyword, $results); // 遞歸子目錄
} else {
// 讀取文件內容
$data = file_get_contents($path);
if ($file === 'search.php') continue; // 排除自身
// 僅搜索 內容,去除 HTML 標籤
if (preg_match('/<body[^>]*>(.+)<\/body>/is', $data, $m)) {
$body = strip_tags($m[1]);
} else {
$body = strip_tags($data);
}
if (stripos($body, $keyword) !== false) {
// 提取標題
if (preg_match('/<title>(.+)<\/title>/i', $data, $t)) {
$title = $t[1];
} else {
$title = "無標題";
}
$results[] = "$path $title";
}
}
}
closedir($handle);
}
listFiles(".", $keyword, $results);
// 輸出結果
foreach ($results as $val) {
list($file, $title) = explode(" ", $val, 2);
echo "<a href='$file'>$title</a><br>";
}
?>
優化要點
- 遞歸遍歷:
opendir/readdir 配合 is_dir 實現深度優先搜索。
- 內容清洗:正則提取
<body> 內容 + strip_tags 去除標籤,僅搜索可見文本。
- 大小寫不敏感:使用
stripos 或 preg_match /i。
- 標題提取:正則捕獲
<title>,增強結果可讀性。
- 超時保護:
set_time_limit(600) 設置 10 分鐘上限。
- 編碼兼容:若文件編碼不一致,需統一轉 UTF-8 後再搜索。
擴展方向
- 引入中文分詞(如 SCWS、Jieba)實現語義搜索。
- 建立倒排索引(如 Sphinx、Elasticsearch)替代實時遍歷,提升大站性能。
- 添加搜索高亮、分頁、權重排序等功能。