Home >Backend Development >PHP Tutorial >Highlight php multiple keywords and highlight the implementation code

Highlight php multiple keywords and highlight the implementation code

WBOY
WBOYOriginal
2016-07-29 08:48:281043browse

Project structure:

 php 多关键字 高亮显示实现代码

Start search: Search keywords here ("big""this")

 php 多关键字 高亮显示实现代码

Search results: Highlight

 php 多关键字 高亮显示实现代码

Project required Database structure:

 php 多关键字 高亮显示实现代码
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';
?>






Keywords:
< ;/td>

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]);
?>

User:




< tr bgColor="#ffffff">

}
?>
Content:

Published date:




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.