Project structure:
Start search: Search keywords here ("big""this")
Search results: Highlight
Project required Database structure:
Implementation code:
conn.php
Copy code The code is as follows:
$conn = @ mysql_connect("localhost", "root", "" ) or die("Database link error");
mysql_select_db("form", $conn);
mysql_query("set names 'gbk'");
?>
searchAndDisplayWithColor.php
Copy code The code is as follows:
include 'conn.php';
?>
cellspacing="1" bgcolor="#add3ef">
//Only perform related searches when the keyword is not empty
if($_GET['keyWord']){
//Separate the keywords with spaces
$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)){
//Replace the keyword, and Highlight the keyword
$row[title]=preg_replace("/$key[0]/i", "$key[0]< /font>", $row[title]);
$row[title]=preg_replace("/$key[0]/i", "$key[1]< ;/b>", $row[title]);
$row[content]=preg_replace("/$key[0]/i", " $key[0]", $row[content]);
$row[content]=preg_replace("/$key[1]/i", "$key[1]", $row[content]);
?>
=$row[title]?> User:=$row[user ] ?>
|
Content: =$row[content]?> |
< tr bgColor="#ffffff">
Published date:=$row[lastdate]?>
|
}
?>
Note: In this small program, one shortcoming is that you can only search for two keys at the same time words, separated by spaces " ". If you only search for a keyword, such as: "big"
garbled characters will appear when displayed... ^|_|^, this is due to the result of the following code:
Copy the code
The code is as follows://Separate the keywords with spaces
$key=explode(' ', $_GET[keyWord]);
If you want to improve, you need to do it later here Make a judgment call.
The above introduces the PHP multi-keyword highlighting implementation code, including the highlighting content. I hope it will be helpful to friends who are interested in PHP tutorials.