【问题标题】:highlighting search results in php error在php错误中突出显示搜索结果
【发布时间】:2023-03-22 02:33:01
【问题描述】:

我试图找出这段代码有什么问题。它要么不突出显示搜索结果,要么在突出显示的文本周围输出 html 标签。 .

$search_result = "";
$search_result = trim($search_result);

$special_cases = array( '%', '_', '+' );
$search_result = str_replace( $special_cases, '',  $_GET["q"] );


//Check if the string is empty
if ($search_result == "") {
  echo  "<p>Search Error</p><p>Please enter a search...</p>" ;
  exit();
      }

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

//eliminating special characters
function h($s) {
    echo htmlspecialchars($s, ENT_QUOTES);
}

 function highlightWords($string, $word)
 {

        $string = str_replace($word, "<span style='background-color: #FFE066;font-weight:bold;'>".$word."</span>", $string);
    /*** return the highlighted string ***/
    return $string;

 }

?>

<div class="caption">Search Results</div>
<div class="center_div">
<table>
    <?php while ($row= mysql_fetch_array($result, MYSQL_ASSOC)) {
        $cQuote =  highlightWords($row['cQuotes'], $search_result);
        ?>
        <tr>
        <td style="text-align:right; font-size:15px;"><?php h($row['cArabic']); ?></td>
            <td style="font-size:16px;"><?php h($cQuote); ?></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>

在浏览器上,输出为:

A good <span style='background-color: #FFE066;font-weight:bold;'>action</span> is an ever-remaining store and a pure yield

或者如果 div 与类一起使用:

A good <div class='highlight'>action</div> is an ever-remaining store and a pure yield

【问题讨论】:

  • html 标签显示为输出,而不是格式化和突出显示关键字。

标签: php html search tags highlight


【解决方案1】:

您的输出函数 h() 正在转义所有 html 字符 (htmlspecialchars)

变化:

$cQuote =  highlightWords($row['cQuotes'], $search_result);

收件人:

$cQuote =  highlightWords(htmlspecialchars($row['cQuotes']), $search_result);

然后改变:

<td style="font-size:16px;"><?php h($cQuote); ?></td>

收件人:

<td style="font-size:16px;"><?php echo $cQuote ?></td>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    • 2017-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2012-02-16
    相关资源
    最近更新 更多