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>
4

2 回答 2

2

您可以使用一个名为HiLite的 JavaScript 库来做到这一点。它工作得很好。

于 2010-04-29T15:24:36.050 回答
2

您可以使用 preg_replace();,当它在您的文本中找到匹配项时,您可以在匹配的单词周围放置一个带有高亮类的 div。然后,您将为突出显示类添加背景颜色和边框以使其突出

preg_replace 期望 3 个参数;

  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 这样做。

于 2010-04-29T16:58:53.300 回答