在php/mysql中突出显示搜索结果

3

如何使用PHP从MySQL查询中突出显示搜索结果?

这是我[修改后的]代码:

$search_result = "";

$search_result = $_GET["q"];

$result = mysql_query('SELECT cQuotes, vAuthor, cArabic, vReference FROM thquotes WHERE cQuotes LIKE "%' . $search_result .'%" ORDER BY idQuotes DESC', $conn)
  or die ('Error: '.mysql_error());


function h($s) {
    echo htmlspecialchars($s, ENT_QUOTES);
} 


?>

    <div class="caption">Search Results</div>
<div class="center_div">
<table>
    <?php while ($row= mysql_fetch_array($result)) { ?>
    <?php $cQuotes = preg_replace($search_result, "<div class='highlight'>".$search_result."</div>", $row['cQuotes']); ?>
        <tr>
            <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']) ?></td>
            <td style="font-size:16px;"><?php h($cQuotes) ?></td>
            <td style="font-size:12px;"><?php h($row['vAuthor']) ?></td>
            <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']) ?></td>
        </tr>
    <?php } ?>
</table>
</div>
2个回答

2
您可以使用 preg_replace() 函数,当它在您的文本中找到匹配项时,您可以在匹配单词周围放置一个类为 highlight 的 div。然后,您可以添加背景颜色和边框到 highlight 类,使其突出显示。 preg_replace() 函数需要三个参数:
1. 第一个参数是您要查找的内容。 2. 第二个参数是应该将其更改为什么。 3. 要从中搜索和替换的文本字符串。
例如:
<div class="center_div">
    <table>
    <caption>Search Results</caption>
    <?php while ($row= mysql_fetch_array($result)) { ?>
<?php $arabic = preg_replace("/".$search_result."/", "<div class='highlight'>".$search_result."</div>", h($row['cArabic'])); ?>
            <tr>
                <td style="text-align:right; font-size:15px;"><?php $arabic ?></td>
                <td style="font-size:16px;"><?php h($row['cQuotes']) ?></td>
                <td style="font-size:12px;"><?php h($row['vAuthor']) ?></td>
                <td style="font-size:12px; font-style:italic; text-align:right;"><?php h($row['vReference']) ?></td>
            </tr>
        <?php } ?>
    </table>
    </div>

我只为阿拉伯语做了这个,但你可能也需要为cQuotes、vAuthor和vReference做同样的事情。


我已经更新了我的答案中的代码,你需要在preg_replace函数的第一个参数前后添加“/”。当我测试代码时,我发现了这个问题并收到了错误信息。我猜你可能关闭了错误报告或者有什么其他原因导致没有显示错误信息。 - Christophe
你在 CSS 文件中为 highlight 类设置样式了吗? - Christophe
是的,我做了。.highlight { background-color: #FFE066; font-weight:bold; } - input
我添加了一个内联样式,它起作用了,你确定你已经正确地链接到你的样式表吗?使用Firebug查看div是否添加到匹配的单词中,并使用Firefox的Web开发者插件检查它是否能找到样式。 - Christophe
我在评论中检查了你的代码,preg_replace('/$search_result/' , '/<span class="highlight">$search_result</span>/', $row['cQuotes']); ?> <- 不要添加单引号,变量在单引号之间不起作用,请使用双引号或像我上面提供的代码一样连接。 - Christophe
显示剩余10条评论

2
你可以使用一个叫做HiLite的JavaScript库来实现这个功能。它运行得相当不错。

谢谢您的回复,但我想用 PHP 来完成。非常感谢任何帮助。 - input

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接