PHP实现搜索关键词描红效果

参考网上的博客,实现简单的搜索结果关键词描红效果。

建库建表sql:

DROP DATABASE IF EXISTS `book`;
CREATE DATABASE IF NOT EXISTS `book` DEFAULT CHARSET = `utf8`;
USE `book`;


SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for tb_book
-- ----------------------------
DROP TABLE IF EXISTS `tb_book`;
CREATE TABLE `tb_book`  (
  `id` int(0) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `name` varchar(255) NOT NULL COMMENT '书名',
  `description` varchar(255) DEFAULT NULL COMMENT '简介',
  PRIMARY KEY (`id`)
) ENGINE = InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tb_book
-- ----------------------------
INSERT INTO `tb_book` VALUES (1, 'Linux从入门到超神', 'Linux学习宝典');
INSERT INTO `tb_book` VALUES (2, 'PHP从菜鸟变高手', 'PHP零基础教学');
INSERT INTO `tb_book` VALUES (3, 'Java从自闭到入坟', 'Java程序员的自我修养');
INSERT INTO `tb_book` VALUES (4, 'C核心思想', '了解C语言编程的核心思想');
INSERT INTO `tb_book` VALUES (5, 'Python之禅', '从入世到出世');

test.php:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>PHP实现关键词描红效果</title>
  <link rel="stylesheet" href="">
</head>
<body>
<form action="#" method="post">
  <input type="search" placeholder="请输入关键词" name="keyword">
  <input type="submit" value="提交" />
</form>
<?php
  if(!empty($_POST['keyword'])){
    $keyword = $_POST['keyword'];//获取输入的关键字
    //进行数据库连接
    $conn = mysqli_connect("localhost","root","123456");
    if(!$conn){
      die("数据库连接失败!");
    }
    $flag = mysqli_select_db($conn,"book");
    if(!$flag){
      die("数据库打开失败!");
    }
    $sql = "select * from tb_book where name like '%$keyword%' or description like '%$keyword%'";
    $result = mysqli_query($conn,$sql);
    while($row = mysqli_fetch_assoc($result)){
?>
<div style="width:300px;height:100px;background-color: #ccc;margin-bottom: 10px">
    <!--使用str_ireplace()函数将结果集中的关键词替换成带样式的(红色字体)-->
  <p>书名:<?php echo str_ireplace($keyword, "<span style=\"color: #f00; \">$keyword</span>",$row['name'])?></p>
  <p>简介:<?php echo str_ireplace($keyword, "<span style=\"color: #f00; \">$keyword</span>",$row['description'])?></p>
</div>
<?php
  }
}else{
  echo "暂未匹配到相关书籍!";
}
?>
</body>
</html>

效果:

点赞