php程序搜索显示高亮

如何去查找呢?利用我们的sql语句中的模糊匹配功能,记住关键字为like.

例如我们想模糊查找$a,只要执行select *form 表 where like ‘%$a%’即可,

如果是首匹配select *form 表 where like ‘$a%,末尾匹配select *form 表 where like ‘$a%

如图

 

 

那么我们在搜索框中填入新华,是不是能把所有含有新华的结果都能查找出来呢?

如图

 

请看代码:

<?php

include("conn.php");

if($_POST["tag"]==1)

{

$sql="select * from infor where name like '%$_POST[sousuo]%'";

$a=mysql_query($sql);

$num=mysql_num_rows($a);

for($i=0;$i<$num;$i++)

{

$b=mysql_fetch_array($a);

echo $b[name]."<br>";

 

}

}

 

 

?>

<form action="#" method="post">

<input type="hidden" name="tag" value="1">

<input type="text" name="sousuo" value="<?php echo $_POST["sousuo"]; ?

>">

<input type="submit" value="搜索">

</form>

如果修改代码$sql="select * from infor where name like '%$_POST[sousuo]'";

大家想一想,搜索结果应该为多少?

我们看图:

 

表示在搜索的内容中以新华结尾的数据,当前信息只有一条。末尾匹配同理不再赘述。

 

有人又说了,我想让查找的结果实现高亮显示该如何实现?

 

没问题,大家还记得我们之前学习过的替换函数没?如果忘记了去查下相关的知识回忆下哦。

看代码:

<?php

include("conn.php");

if($_POST["tag"]==1)

{

$sql="select * from infor where name like '%$_POST[sousuo]%'";

$a=mysql_query($sql);

$num=mysql_num_rows($a);

for($i=0;$i<$num;$i++)

{

$b=mysql_fetch_array($a);

echo str_replace( $_POST[sousuo],"<font color=red>".$_POST

[sousuo]."</font>",$b[name])."<br>";

 

}

}

 

 

?>

<form action="#" method="post">

<input type="hidden" name="tag" value="1">

<input type="text" name="sousuo" value="<?php echo $_POST["sousuo"]; ?

>">

<input type="submit" value="搜索">

</form>

用一个简单的替换函数让查找结果与众不同了,就实现高亮搜索了。

看图:

 

综上所述就是php中实现模糊搜索和高亮显示的方法,(*^__^*) 。所用的知识我都已经讲过,不清楚的函数大家要勤查php手册。

posted on 2013-08-31 14:55  一阵寒风  阅读(380)  评论(0)    收藏  举报

导航