Home  >  Article  >  php教程  >  看PHP如何实现多关键字加亮

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

WBOY
WBOYOriginal
2016-06-21 08:51:551054browse

  项目结构:

 

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

  搜索结果: 高亮显示

  项目所需数据库结构:

  实现代码:

  conn.php

 

  

  $conn = @ mysql_connect("localhost", "root", "") or die("数据库链接错误");

  mysql_select_db("form", $conn);

  mysql_query("set names 'gbk'");

  ?>

 

  searchAndDisplayWithColor.php

include 'conn.php'; 
?> 

 
      
      
          
      
      
 
关键字: 
        
 
  
 
     cellspacing="1" bgcolor="#add3ef"> 
          //关键字不为空的时候才执行相关搜索 
     if($_GET['keyWord']){ 
     //用空格符把关键字分割开 
     $key=explode(' ', $_GET[keyWord]); 
     $sql="select * from message where title like '$key[0]' or title like '$key[1]' or content like '$key[0]' or content like '%$key[1]%'"; 
     $query=mysql_query($sql); 
     while ($row=mysql_fetch_array($query)){ 
         //替换关键字,并且把关键字高亮显示 
         $row[title]=preg_replace("/$key[0]/i", "$key[0]", $row[title]); 
         $row[title]=preg_replace("/$key[0]/i", "$key[1]", $row[title]); 
         $row[content]=preg_replace("/$key[0]/i", "$key[0]", $row[content]); 
         $row[content]=preg_replace("/$key[1]/i", "$key[1]", $row[content]); 
         ?> 
  
      
         标题:=$row[title]?> 用户:=$row[user] ?> 
        
编辑                  href="delete.php?id==$row[id]?>">删除
 
          
      
      
         内容:=$row[content]?> 
      
      
          
        
发表日期:=$row[lastdate]?>
 
          
      
          } 
     ?> 
 

 

  说明:在这个小程序中,有一点不足之处在于,只能同时搜索两个关键字,并且中间用空格" "隔开,如果只是搜索一个关键字,如:"大"

  显示的时候会出现乱码 ……^_^,这是由于下面代码的结果:

  //用空格符把关键字分割开

  $key=explode(' ', $_GET[keyWord]);

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



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn