关键词高亮在PHP中实现相对很简单,他只需要获取利用提取过来的关键词进行分词然后再利用str_replace()函数来实现替换就可以原理相对很简单。
给加色的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", $row[content]);
- $row[content]=preg_replace("/$key[1]/i", $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]);
如果要改进的话,在这里的后面就要做一下判断了。
总结:上面的关键词高亮只是一个非常简单的用户提交过来什么我们就对这个关键词进行了str_replace进行高亮显示了,如果要做得更好可利用Dedecms分词系统进行分词再操作会好很多哦。