簡體   English   中英

如何突出MySQL搜索結果中的關鍵字

[英]How to highlight keywords in MySQL search results

有沒有一種簡單的方法可以在結果中突出顯示搜索到的關鍵字? 該項目是一個博客。 搜索功能很有用,但我想強調搜索找到的單詞。

這是我的代碼:

/*-------------------------  Search    -------------------------------*/  
if(isset($_GET['action']) && $_GET['action'] === 'search'){

    // Connect to database
    include 'includes/dbconnect.php';

    // Check if input box is empty
    if( empty($_GET['search_query']) ){

        $errMsg = 'Please enter data to search.';
        include 'includes/error.html.php';
        exit();       
    } 
    else { 

        // Sanitize user data
        $search = htmlspecialchars($_GET['search_query']);

        // Store $search content into $_SESSIONS['search'] for use below
        $_SESSION['search'] = $search;

    }  

    try {
        $sql = "SELECT post_id, post_category_id, post_title, post_date, post_author, post_keywords, post_image, post_content, cat_title
                FROM posts
                INNER JOIN categories
                ON post_category_id = cat_id
                WHERE post_content LIKE '%$search%'
                OR post_title LIKE '%$search%'
                OR post_author LIKE '%$search%'
                OR post_keywords LIKE '%$search'"; 

        $s = $db->prepare($sql);
        $s->execute();
    } 
    catch (PDOException $e) {
        $errMsg = 'Error fetching data' . $e->getMessage();
        include 'includes/error.html.php';
        exit();
    }

     if($s->rowCount() < 1){
            $errMsg = 'Sorry, no match found for: ' . $_SESSION['search'];
            include 'includes/error.html.php';
            exit();
    } else {

        if($s->rowCount() > 0){
            while($row = $s->fetch(PDO::FETCH_ASSOC)){
                $posts[] = array(
                    'post_id' => $row['post_id'],  
                    'post_category_id' => $row['post_category_id'],
                    'post_title' => $row['post_title'],
                    'post_date' => $row['post_date'],
                    'post_author' => $row['post_author'],
                    'post_keywords' => $row['post_keywords'],
                    'post_image' => $row['post_image'],
                    'post_content' => substr($row['post_content'], 0,240),  //http://php.net/manual/en/function.substr.php
                    'cat_title' => $row['cat_title'],
                );
            }                
        }
    } 

    // Close database connection
    $db = null;

    include 'results.html.php';
    exit();
} 

謝謝你的幫助。

在創建輸出時,在每個結果中圍繞搜索詞包裝具有適當類的span ,例如

echo str_replace($search, "<span class='highlight'>$search</span>", $post['post_content']);

根據您的查詢,您希望在多個字段中查找搜索字符串,但是為了提高效率,最好將特定搜索區域組合在一起,如下所示:

$searcharray = [
  $posts['post_title'],
  $posts['post_author'],
  $posts['post_keywords'],
  $posts['post_title']
];

現在要查找要替換的數據,遍歷數組並替換它的內容:

foreach($posts as $k => $post){ // loop over main array;
  $searcharray = [
    $posts['post_title'],
    $posts['post_author'],
    $posts['post_keywords'],
    $posts['post_title']
  ];

  foreach($searcharray as $key => $val){ // loop over each post found.
    $posts[$k][$key] = str_replace($search, "<em>$search</em>", $val);
  }
}

在旁注:

根據您從數據庫中提取的數據量,這可能是瓶頸。 你知道嗎 就個人而言,我最喜歡這樣做的方法是讓客戶自己做。 像普通的那樣打印出數據並插入包含搜索屬性的元素或直接將其打印到Javascript並在特定元素上執行正則表達式來替換客戶端的文本。 這樣,服務器可以執行與服務器相關的操作,而不是照顧最終用戶。

看看這個 ,構建為jQuery的插件,非常容易使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM