php做站內搜尋並高亮顯示關鍵字_PHP教程

來源:互聯網
上載者:User
本文章介紹一篇較實用的文章關於php做站內搜尋並高亮顯示關鍵字,這個很多朋友直接利用preg_replace來操作,這是正確的哦,不過我覺得用str_replace更快一些哦。至於原因自己查查這兩個函數的區別吧。

如何使用php做站內搜尋並高亮顯示關鍵字?

代碼如下 複製代碼

require_once 'sqlTools.class.php';//封裝類,可執行dql、dml語句

$info=$_POST['info'];

$sql="select name,password,email from user_500 where name like '%$info%' or password like '%$info%' or email like '%$info%'";

$sqlTools=new SqlTools();

$res=$sqlTools->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);//這種方式能對以空格隔開的關鍵字進行分割,再對分割後的結果挨個進行查詢,同樣,可以使用Regex函數進行替換工作,以高亮顯示關鍵字

代碼如下 複製代碼

sqlTools.class.php的原始碼:

class SqlTools{

private $host="localhost";

private $dbname="test";

private $dbuser="root";

private $dbpwd="";

private $conn;

public function __construct(){

$this->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);

}

}

?>

http://www.bkjia.com/PHPjc/631657.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631657.htmlTechArticle本文章介紹一篇較實用的文章關於php做站內搜尋並高亮顯示關鍵字,這個很多朋友直接利用preg_replace來操作,這是正確的哦,不過我覺得用...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.