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

时间:2016-03-03 13:02:12

标签: php highlight str-replace

我试图在PHP搜索中突出显示我的搜索结果,但它突出了不受欢迎的

我使用下面的代码

//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);

假设我搜索 makutano 这个词 我最终得到的结果如下所示:

enter image description here

我希望它只是突出显示makutano,但它不能按预期工作。

如果我删除str_replace($searchTerm, "<span style='background-color:pink;'>$searchTerm</span>"代码,我的结果将在下面的图片中显示

enter image description here

我的数据库位置如下

enter image description here

我的代码在哪里出错了?任何帮助将不胜感激

1 个答案:

答案 0 :(得分:3)

如果要显示连接字符串的信息(我使用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;

创建字符串后,您可以执行替换以将标记添加到字符串中。

Your script is at risk for SQL Injection Attacks.了解preparedMySQLi语句。我使用htmlspecialchars()完成了此代码中的最低限度。