0
<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. 我得到一个关键字突出显示,但如果我搜索两个关键字,我会得到多个重复。有些突出一些没有。你们能否给我一些指示如何修复此代码。谢谢你。

4

1 回答 1

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;
于 2013-08-13T13:37:40.580 回答