简体   繁体   English

PHP中的突出显示搜索关键字无法正确突出显示

[英]Highlight search keyword in PHP does not highlight correctly

I am trying to highlight my search result in PHP search but it highlights undesiraby 我试图在PHP搜索中突出显示我的搜索结果,但突出显示undesiraby

I use the code below 我使用下面的代码

//connection to db
define('DB_HOST', 'localhost');
define('DB_NAME', 'dbname');
define('DB_USERNAME','root');
define('DB_PASSWORD','');

$con = mysqli_connect(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if( mysqli_connect_error()) echo "Failed to connect to MySQL: " . mysqli_connect_error();


//get search term
$searchTerm = $_GET['term'];

$result = mysqli_query($con, "SELECT `location` FROM `locations` WHERE TRIM(location) LIKE '%".($_GET['term'])."%'");   

$data = array();
while ($row = mysqli_fetch_assoc($result)) 
{

        $name = str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>", $row['location']); 
        array_push($data, $name);   
}   



//return json data

echo json_encode($data);

Lets say I search for the term makutano I end up getting a result like the one displayed below: 可以说,我搜索术语makutano时 ,最终得到的结果如下所示:

在此处输入图片说明

I would expect it only to highlight makutano , but it does not work as intended. 我希望它仅突出显示makutano ,但它不能按预期工作。

If i remove the str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>" code my result would be as diplayed in the image below 如果我删除了str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>"代码,我的结果将如下图所示

在此处输入图片说明

My database location looks like 我的数据库位置看起来像

在此处输入图片说明

Where am i going wrong from my code? 我的代码在哪里出错? Any help will be appreciated 任何帮助将不胜感激

If you want to display the information you have to concatenate a string (which I do with the implode() )instead of creating a JSON object: 如果要显示信息,则必须连接一个字符串(我使用implode() )而不是创建JSON对象:

//get search term
$searchTerm = htmlspecialchars($_GET['term']);

$result = mysqli_query($con, "SELECT `location` FROM `locations` WHERE TRIM(`location`) LIKE '%".($_GET['term'])."%'");   

$data = array();
while ($row = mysqli_fetch_assoc($result)) 
{
    $name = $row['location']; 
    array_push($data, $name);   
}   

$string = '"' . implode('","', $data) . '"';
$newString = str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>", $string); 
echo $newString;

Once you have created a string then you can do the replace to add the markup to the string. 一旦创建了字符串,就可以进行替换以将标记添加到字符串中。


Your script is at risk for SQL Injection Attacks. 您的脚本受到SQL注入攻击的威胁。 Learn about prepared statements for MySQLi . 了解有关MySQLi的 准备好的语句。 I have done the bare minimum in this code by using htmlspecialchars() . 我已经使用htmlspecialchars()在此代码中完成了最低限度的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM