当前位置:Gxlcms > PHP教程 > 看PHP如何实现多关键字加亮_PHP教程

看PHP如何实现多关键字加亮_PHP教程

时间:2021-07-01 10:21:17 帮助过:13人阅读

项目结构:

\

开始搜索: 这里搜索关键字("大""这")

\

搜索结果: 高亮显示

\

项目所需数据库结构:

\

实现代码:

conn.php

  1. $conn = @ mysql_connect("localhost", "root", "") or die("数据库链接错误");
  2. mysql_select_db("form", $conn);
  3. mysql_query("set names 'gbk'");
  4. ?>

searchAndDisplayWithColor.php

  1. include 'conn.php';
  2. ?>
  3. "center">
  4. "0" align="center" cellpadding="5"
  5. cellspacing="1" bgcolor="#add3ef">
  6. //关键字不为空的时候才执行相关搜索
  7. if($_GET['keyWord']){
  8. //用空格符把关键字分割开
  9. $key=explode(' ', $_GET[keyWord]);
  10. $sql="select * from message where title like '$key[0]' or title like '$key[1]' or content like '$key[0]' or content like '%$key[1]%'";
  11. $query=mysql_query($sql);
  12. while ($row=mysql_fetch_array($query)){
  13. //替换关键字,并且把关键字高亮显示
  14. $row[title]=preg_replace("/$key[0]/i", "$key[0]", $row[title]);
  15. $row[title]=preg_replace("/$key[0]/i", "$key[1]", $row[title]);
  16. $row[content]=preg_replace("/$key[0]/i", "$key[0]", $row[content]);
  17. $row[content]=preg_replace("/$key[1]/i", "$key[1]", $row[content]);
  18. ?>
  19. "#eff3ff">
  20. "#ffffff">
  21. "#ffffff">
  22. }
  23. ?>
  24. 标题:"black">$row[title]?> 用户:"black">$row[user] ?>
  25. "right">"preEdit.php?id=">编辑 |
  26. href="delete.php?id=">删除
  27. 内容:$row[content]?>
  28. "right">发表日期:$row[lastdate]?>

说明:在这个小程序中,有一点不足之处在于,只能同时搜索两个关键字,并且中间用空格" "隔开,如果只是搜索一个关键字,如:"大"
显示的时候会出现乱码 ……^|_|^,这是由于下面代码的结果:

  1. //用空格符把关键字分割开
  2. $key=explode(' ', $_GET[keyWord]);

如果要改进的话,在这里的后面就要做一下判断了。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/445701.htmlTechArticle项目结构: 498)this.width=498;' onmousewheel = 'javascript:return big(this)' height="183" alt="\" width="274" src="http://www.bkjia.com/uploadfile/2013/0904/2013090409540695...

人气教程排行