在 PHP 搜索脚本中突出显示关键字 [英] Highlighting keywords in PHP search script
问题描述
我有一个 PHP 搜索脚本,用于查询 MySQL 数据库,然后通过 HTML 解析结果以允许 CSS 样式.我希望脚本突出显示用户搜索结果中的所有关键字.我怎样才能用 PHP 做到这一点?
I have a PHP search script that queries a MySQL database and then parses the results through HTML to allow CSS styling. I want the script to highlight all of the keywords in the results that the user has search for. How can I do this with PHP?
我的 PHP 脚本是:
My PHP script is:
<?php
mysql_connect("localhost","username","password");
mysql_select_db("database");
if(!empty($_GET['q'])){
$query=mysql_real_escape_string(trim($_GET['q']));
$searchSQL="SELECT * FROM links WHERE `title` LIKE '%{$query}%' LIMIT 8";
$searchResult=mysql_query($searchSQL);
while ($row=mysql_fetch_assoc($searchResult)){
$results[]="<a href='{$row['url']}' class='webresult'><div class='title'>{$row['title']}</div><div class='desc'>{$row['description']}</div><div class='url'>{$row['url']}</div></a>";
}
if(empty($results)){
echo 'No results were found';
} else {
echo implode($results);
}
}
?>
推荐答案
简单地说,您可以在此处调整循环:
Simplistically you could adapt the loop here:
$searchvar = trim($_GET['q']);
while ($row=mysql_fetch_assoc($searchResult)){
$description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
$results .="<a href='{$row['url']}' class='webresult'>
<div class='title'>{$row['title']}</div>
<div class='desc'>{$description}</div>
<div class='url'>{$row['url']}</div></a>";
}
为了让它变得更好:
$searchvar = explode(" ", trim($_GET['q'])); //puts each space separated word into the array.
while ($row=mysql_fetch_assoc($searchResult)){
$description = $row['description'];
foreach($searchvar as $var) $description = str_replace($var, '<span class="highlight">'.$var."</span>", $description);
$description = str_replace($searchvar, '<span class="highlight">'.$searchvar."</span>", $row['description']);
$results .="<a href='{$row['url']}' class='webresult'>
<div class='title'>{$row['title']}</div>
<div class='desc'>{$description}</div>
<div class='url'>{$row['url']}</div></a>";
}
第二个的好处是,如果用户输入ipod toudch yellow",您将搜索ipod"、toudch"和yellow",这将否定类型并使结果更一般.
The benefit of the second one there is that if a user types in "ipod toudch yellow" you will be searching for "ipod", "toudch" and "yellow" which would negate the type and make the results more general.
您需要更换单曲:
like '%query%'
与
foreach(explode(" ", trim($_GET['q']) as $searchvar) $where[] = "like '%$searchvar%'";
$wheresql = implode(" OR ", $where);
要在 sql 中查找要查找的每个搜索单词",否则您将进行有限的搜索并带有不相关的突出显示.
to get each search "word" to be looked for in the sql or you will have a limited search with a unrelated highlight.
这篇关于在 PHP 搜索脚本中突出显示关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!