突出显示Mysql搜索。但preg_replace无法正常工作?

时间:2013-08-13 13:31:48

标签: php mysql

<h2>Search</h2> 
<form name="search" method="post" action="<?=$PHP_SELF?>">
Search for: <input type="text" name="find" />
<select name="field">
<option VALUE="name">Name</option>
<option VALUE="location">Location</option>
</select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" value="Search" />
</form>

<? 
//This is only displayed if they have submitted the form 

$find = $_POST['find'];
$field = $_POST['field'];
$searching = $_POST['searching'];

if ($searching =="yes") 
{ 
//echo "<h2>Results</h2><p>"; 

//If they did not enter a search term we give them an error 
if ($find == "") 
{ 
echo "<p>You forgot to enter a search term"; 
exit; 
} 

// Otherwise we connect to our Database 
mysql_connect("localhost", "DB_name", "Password") or die(mysql_error()); 
mysql_select_db("wine") or die(mysql_error()); 

// We preform a bit of filtering 
//$find = strtoupper($find); 
//$find = strip_tags($find); 
//$find = trim ($find); 

$find = mysql_real_escape_string($find);
echo "<br><br><br><font size=5>Searched results for:</b> " .$find; 
echo "</font><br><br>"; 
//Now we search for our search term, in the field the user specified 
$data = mysql_query("SELECT * from
(select * FROM chardonnay WHERE MATCH $field AGAINST('%".$find."%' IN BOOLEAN MODE)
union 
select * from pinotnoir WHERE MATCH $field AGAINST('%".$find."%' IN BOOLEAN MODE)
union 
select * from redwines1 WHERE MATCH $field AGAINST('%".$find."%' IN BOOLEAN MODE)
union 
select * from redwines2 WHERE MATCH $field AGAINST('%".$find."%' IN BOOLEAN MODE)
union 
select * from redwines3 WHERE MATCH $field AGAINST('%".$find."%' IN BOOLEAN MODE)
union
select * from redwines4 WHERE MATCH $field AGAINST('%".$find."%' IN BOOLEAN MODE))
a order by grape, name
"); 

while($result = mysql_fetch_array( $data )) 
{ 

 //And we display the results 

$explode_criteria = explode(" ", $_GET['find']);
$highlight = $result['name']; // capture $result['name'] here
foreach ($explode_criteria as $key)
{

// escape the user input
$key2 = preg_quote($key, '/');
// keep affecting $highlight
$highlight = preg_replace( "/" .$key2. "/", "<span style='color: red'>".$key."    </span>", $highlight);


echo $highlight;
}

我正在尝试突出显示多个搜索字词。我在这个网站上搜索过,但这是我能理解的最简单的代码。但不知怎的,它不起作用。如果我将$ _GET ['find']更改为$ find。我得到一个关键字突出显示,但如果我搜索两个关键字,我得到多个重复。有人强调一些不是。你能给我一些指针如何修复这段代码。谢谢。

1 个答案:

答案 0 :(得分:0)

至少,在你完成所有替换之前,你不应该回复$highlight。实际上,每次搜索$key

时都会回显它
foreach ($explode_criteria as $key)
{
  // escape the user input
  $key2 = preg_quote($key, '/');
  // keep affecting $highlight
  $highlight = preg_replace( "/" .$key2. "/", "<span style='color: red'>".$key."    </span>", $highlight);
}    

echo $highlight;