作者:减肥瘦身666 | 来源:互联网 | 2018-03-22 02:02
本文章介绍一篇较实用的文章关于php做站内搜索并高亮显示关键字,这个很多朋友直接利用preg_replace来操作,这是正确的哦,不过我觉得用str_replace更快一些哦,至于原因自己查查这...
本文章介绍一篇较实用的文章关于php做站内搜索并高亮显示关键字,这个很多朋友直接利用preg_replace来操作,这是正确的哦,不过我觉得用str_replace更快一些哦,至于原因自己查查这两个函数的区别吧。
如何使用php做站内搜索并高亮显示关键字?代码如下:
execute_dql($sql);
while ($row = mysql_fetch_assoc($res)) {
$row['name'] = preg_replace("/($info)/i", "1", $row['name']);
$row['password'] = preg_replace("/($info)/i", "1", $row['password']);
$row['email'] = preg_replace("/($info)/i", "1", $row['email']);
echo $row['name'] . "-->" . $row['password'] . "-->" . $row['email'] . "
";
}
?>
思路分析:将sql语句中包含的%$info%交给DBMS执行的时候,他会查找字段中含有变量$info的值的信息,
%$info--->查找以$info的值结束的信息
$info%--->查找以$info的值开头的信息
通过正则函数preg_replace()将搜索到的关键字高亮显示,比如:
$row['name']=preg_replace("/($info)/i","1",$row['name']);
的意思是:通过POST方接收到的值$info替换为加上样式(红色加粗)的结果,并将结果重新赋给$row[‘name’]
如果要搜索多个关键字的话,可以对接收到值$info进行分割,比如$info_more=explode(" ",$info);//这种方式能对以空格隔开的关键字进行分割,再对分割后的结果挨个进行查询,同样,可以使用正则表达式函数进行替换工作,以高亮显示关键字,代码如下:
sqlTools.class.php的源代码:
cOnn= mysql_connect($this->host, $this->dbuser, $this->dbpwd);
if (!$this->conn) {
die("连接数据库失败" . mysql_error());
}
mysql_select_db($this->dbname, $this->conn) or die("找不到该数据库" . mysql_error());
mysql_query("set names utf8");
}
public function execute_dml($sql) {
$bool = mysql_query($sql);
if ($bool) {
if ($bool > 0) {
return 1;
} else {
return 2;
}
} else {
return 0;
}
}
public function execute_dql($sql) {
$res = mysql_query($sql);
return $res;
}
public function close_conn() {
mysql_close($this->conn);
}
}
?>
本文链接:
收藏随意^^请保留教程地址.