php 多关键字 高亮显示实现代码

yipeiwu_com5年前PHP代码库

项目结构:

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

搜索结果:  高亮显示

项目所需数据库结构:


实现代码:
conn.php

复制代码 代码如下:

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

searchAndDisplayWithColor.php
复制代码 代码如下:

<?php
include 'conn.php';
?>

<table width=500 align="center">
<form action="" method="get">
<tr>
<td>关键字:<input type="text" name="keyWord" />
<input type="submit" value="搜索" /></td>
</tr>
</form>
</table>

<table width=500 border="0" align="center" cellpadding="5"
cellspacing="1" bgcolor="#add3ef">
<?php
//关键字不为空的时候才执行相关搜索
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", "<font color=red><b>$key[0]</b></font>", $row[title]);
$row[title]=preg_replace("/$key[0]/i", "<font color=red><b>$key[1]</b></font>", $row[title]);
$row[content]=preg_replace("/$key[0]/i", "<font color=red><b>$key[0]</b></font>", $row[content]);
$row[content]=preg_replace("/$key[1]/i", "<font color=red><b>$key[1]</b></font>", $row[content]);
?>

<tr bgcolor="#eff3ff">
<td>标题:<font color="black"><?=$row[title]?></font> 用户:<font color="black"><?=$row[user] ?></font>
<div align="right"><a href="preEdit.php?id=<?=$row[id]?>">编辑</a>  |  <a
href="delete.php?id=<?=$row[id]?>">删除</a></div>
</td>
</tr>
<tr bgColor="#ffffff">
<td>内容:<?=$row[content]?></td>
</tr>
<tr bgColor="#ffffff">
<td>
<div align="right">发表日期:<?=$row[lastdate]?></div>
</td>
</tr>
<?php }
}
?>
</table>

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

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

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

相关文章

PHP小偷程序的设计与实现方法详解

本文实例讲述了PHP小偷程序的设计与实现方法。分享给大家供大家参考,具体如下: 其实自己一直想做一个内涵图片的网站,以前的想法是做一个CMS,然后自己上传一些图片。。 开始真这么做的,没...

Cakephp 执行主要流程

加载基本文件 cake/basics.php 里面定义了常用的方法以及时间常量 $TIME_START = getMicrotime(); 记录开始执行时间 cake/config/pa...

PHP函数实现从一个文本字符串中提取关键字的方法

本文实例讲述了PHP函数实现从一个文本字符串中提取关键字的方法。分享给大家供大家参考。具体分析如下: 这是一个函数定位接收一个字符串作为参数(连同其他配置可选参数),并且定位该字符串中的...

PHP获取数组中某元素的位置及array_keys函数应用

众所周知,PHP自身内置了很多函数,这也是使用PHP能够极大提高开发效率的一个重要原因,获取数组中一元素的位置有很多方法,其中PHP自身就已经内置了一个函数array_keys(),下边...

浅析Yii中使用RBAC的完全指南(用户角色权限控制)

写在前面    * 我的feed地址已经修改为: http://feeds.imdong.net ,请更新您的阅读器。   ...