简体   繁体   中英

How to highlight keywords in MySQL search results

Is there a simple way to highlight the searched keywords in the results? The project is a blog. The search function works great, but I would like to highlight the words the search finds.

Here's my code:

/*-------------------------  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();
} 

Thanks for any assistance.

在创建输出时,在每个结果中围绕搜索词包装具有适当类的span ,例如

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

According your your query, you want to look for the search string in multiple fields, however for efficiency sake, its better to group the specific search area's together like so:

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

Now to look for the data you want to replace, loop over the array and replace the content of it:

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);
  }
}

On a side note:

Depending on the amount of data you fetch from the database this could be a bottle neck. Just so you know. Personally, my favorite way of doing this is let the client do it themselves. Print out the data like normal and insert somewhere an element that contains the search attribute or print it directly to Javascript and execute a regex over specific elements to replace the text for the client. This way the server can do server related stuff instead of taking care of the end-user.

Take a look at this , build as a plugin for jQuery and very easy to use

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM