純靜態 HTML 網站(Dreamweaver/FrontPage 產出),無資料庫,需提供關鍵字搜尋功能。透過 PHP 遞迴掃描檔案、解析內容、建立索引陣列即可實作簡易搜尋引擎。
opendir/readdir)file_get_contents)<body> 區塊並移除 HTML 標籤(strip_tags)preg_match,大小寫不敏感)<title> 作為標題<?php
set_time_limit(600); // 防止大量檔案逾時
$keyword = trim($_POST['keyword'] ?? '');
if ($keyword === '') {
exit('請輸入搜尋關鍵字');
}
// 安全:僅允許字母數字中文,防正則注入
$keyword = preg_quote($keyword, '/');
$results = [];
searchFiles('.', $keyword, $results);
function searchFiles($dir, $keyword, &$results) {
$handle = opendir($dir);
while (false !== ($file = readdir($handle))) {
if ($file === '.' || $file === '..') continue;
$path = "$dir/$file";
if (is_dir($path)) {
searchFiles($path, $keyword, $results);
} elseif (is_file($path) && $file !== 'search.php') {
$content = @file_get_contents($path);
if ($content === false) continue;
// 提取 body 內容
if (preg_match('/<body[^>]*>(.+)<\/body>/is', $content, $m)) {
$body = strip_tags($m[1]);
} else {
$body = strip_tags($content);
}
if (preg_match("/$keyword/i", $body)) {
// 提取 title
$title = '無標題';
if (preg_match('/<title>(.+)<\/title>/i', $content, $tm)) {
$title = trim($tm[1]);
}
$results[] = ['path' => $path, 'title' => $title];
}
}
}
closedir($handle);
}
// 輸出結果
foreach ($results as $r) {
echo "<a href='{$r['path']}' target='_blank'>{$r['title']}</a><br>\n";
}
if (empty($results)) echo '找不到相關結果';
?>
pcntl_fork 或多程序分割目錄加速preg_quote 轉義防正則注入open_basedir 限制 PHP 存取路徑