This article introduces a more practical article about php on-site search and highlighting keywords. Many friends directly use preg_replace to operate this. This is correct, but I think it is faster to use str_replace. As for the reason, check the difference between the two functions yourself.
How to use php to do on-site search and highlight keywords?
The code is as follows | Copy code | ||||
"; } ?> |
Think analysis:
When the %$info% contained in the sql statement is handed over to the DBMS for execution, it will look for information containing the value of the variable $info in the field,
%$info--->Find information ending with the value of $info
$info%--->Find information starting with the value of $info
Highlight the searched keywords through the regular function preg_replace(), for example,
$row['name']=preg_replace("/($info)/i","1",$row['name'] );
means: replace the value $info received through the POST party with the result with style (red bold), and reassign the result to $row[‘name’]
If you want to search for multiple keywords, you can split the received value $info, such as $info_more=explode(" ",$info);//This method can search for keywords separated by spaces. Split, and then query the split results one by one. Similarly, you can use the regular expression function to perform replacement to highlight the keyword
The code is as follows | Copy code |
Source code of 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("Failed to connect to database".mysql_error()); } mysql_select_db($this->dbname,$this->conn) or die("The database cannot be found".mysql_error()); mysql_query("set names utf8"); } public function execute_dml($sql){ $bool=mysql_query($sql); if ($bool){ if ($bool>0) { return 1; return 2; } }else { return 0; } } public function execute_dql($sql){ $res=mysql_query($sql); return $res; } public function close_conn(){ mysql_close($this->conn); } } ?> |