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

preg_replace(); を使用できます。テキスト内で一致が見つかった場合は、一致する単語の周りにハイライトのクラスを持つ div を配置できます。次に、背景色と境界線をハイライト クラスに追加して、目立たせます。

preg_replace には 3 つのパラメーターが必要です。

  1. 最初のものはあなたが探しているものです
  2. 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 に答える
2

これは、 HiLiteという JavaScript ライブラリを使用して行うことができます。それはかなりうまくいきます。

于 2010-04-29T15:24:36.050 に答える