php搜索功能实现
PHP 搜索功能实现
在 PHP 中实现搜索功能可以通过多种方式完成,具体取决于需求和数据存储方式。以下是几种常见的实现方法:
数据库全文搜索(MySQL)
使用 MySQL 的 LIKE 或全文索引(FULLTEXT)实现搜索功能。
-- 创建支持全文索引的表
CREATE TABLE articles (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
content TEXT,
FULLTEXT(title, content)
) ENGINE=InnoDB;
// PHP 代码示例
$searchTerm = $_GET['q'] ?? '';
$conn = new mysqli("localhost", "username", "password", "database");
// 使用 LIKE 简单搜索
$stmt = $conn->prepare("SELECT * FROM articles WHERE title LIKE ? OR content LIKE ?");
$searchTermLike = "%$searchTerm%";
$stmt->bind_param("ss", $searchTermLike, $searchTermLike);
$stmt->execute();
$result = $stmt->get_result();
// 使用 FULLTEXT 更高效的搜索
$stmt = $conn->prepare("SELECT * FROM articles WHERE MATCH(title, content) AGAINST(?)");
$stmt->bind_param("s", $searchTerm);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// 处理结果
}
使用 Elasticsearch 实现高级搜索
对于大型应用,Elasticsearch 提供更强大的搜索能力。
// 安装 Elasticsearch PHP 客户端
// composer require elasticsearch/elasticsearch
require 'vendor/autoload.php';
$client = Elastic\Elasticsearch\ClientBuilder::create()->build();
$params = [
'index' => 'articles',
'body' => [
'query' => [
'multi_match' => [
'query' => $searchTerm,
'fields' => ['title', 'content']
]
]
]
];
$response = $client->search($params);
$hits = $response['hits']['hits'];
foreach ($hits as $hit) {
// 处理结果
}
文件内容搜索
如果需要搜索文件内容,可以使用 PHP 文件函数结合正则表达式。
$directory = '/path/to/files';
$searchTerm = $_GET['q'] ?? '';
$results = [];
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$content = file_get_contents("$directory/$file");
if (preg_match("/$searchTerm/i", $content)) {
$results[] = $file;
}
}
}
closedir($handle);
}
// 显示结果
foreach ($results as $file) {
echo "Found in: $file<br>";
}
提高搜索体验的技巧
-
对搜索词进行清理,防止 SQL 注入
$searchTerm = htmlspecialchars(strip_tags($searchTerm)); -
添加分页功能
LIMIT $offset, $perPage -
实现高亮显示匹配内容
echo preg_replace("/$searchTerm/i", "<span class='highlight'>$0</span>", $text); -
记录热门搜索词
INSERT INTO search_log (term, count) VALUES (?, 1) ON DUPLICATE KEY UPDATE count = count + 1
以上方法可以根据具体需求选择或组合使用。对于小型项目,数据库全文搜索足够;对于大型项目,Elasticsearch 能提供更好的性能和功能。






