繁体   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