项目结构:
开始搜索: 这里搜索关键字("大""这")
搜索结果: 高亮显示
项目所需数据库结构:
================================================================
实现代码:
================================================================
conn.php
1 <?php2 $conn = @ mysql_connect("localhost", "root", "") or die("数据库链接错误");3 mysql_select_db("form", $conn);4 mysql_query("set names 'gbk'"); 5 ?>
searchAndDisplayWithColor.php
1 <?php 2 include 'conn.php'; 3 ?> 4 5 <table width=500 align="center"> 6 <form action="" method="get"> 7 <tr> 8 <td>关键字:<input type="text" name="keyWord" /> 9 <input type="submit" value="搜索" /></td>10 </tr>11 </form>12 </table>13 14 <table width=500 border="0" align="center" cellpadding="5"15 cellspacing="1" bgcolor="#add3ef">16 <?php17 //关键字不为空的时候才执行相关搜索18 if($_GET['keyWord']){19 //用空格符把关键字分割开20 $key=explode(' ', $_GET[keyWord]);21 $sql="select * from message where title like '$key[0]' or title like '$key[1]' or content like '$key[0]' or content like '%$key[1]%'";22 $query=mysql_query($sql);23 while ($row=mysql_fetch_array($query)){24 //替换关键字,并且把关键字高亮显示25 $row[title]=preg_replace("/$key[0]/i", "<font color=red><b>$key[0]</b></font>", $row[title]);26 $row[title]=preg_replace("/$key[0]/i", "<font color=red><b>$key[1]</b></font>", $row[title]);27 $row[content]=preg_replace("/$key[0]/i", "<font color=red><b>$key[0]</b></font>", $row[content]);28 $row[content]=preg_replace("/$key[1]/i", "<font color=red><b>$key[1]</b></font>", $row[content]);29 ?>30 31 <tr bgcolor="#eff3ff">32 <td>标题:<font color="black"><?=$row[title]?></font> 用户:<font color="black"><?=$row[user] ?></font>33 <div align="right"><a href="preEdit.php?id=<?=$row[id]?>">编辑</a> | <a34 href="delete.php?id=<?=$row[id]?>">删除</a></div>35 </td>36 </tr>37 <tr bgColor="#ffffff">38 <td>内容:<?=$row[content]?></td>39 </tr>40 <tr bgColor="#ffffff">41 <td>42 <div align="right">发表日期:<?=$row[lastdate]?></div>43 </td>44 </tr>45 <?php }4