eveo
eveo

Reputation: 2833

Highlighting a search term in a query?

I'm having trouble highlighting a search term within a query. If a user searches "Jesus", all verses that contain "Jesus" will be listed and paginated. I want to highlight the search query in all of these passages.

Let's say I search for "Jesus", and some 10 verses pop up, I want all instances of Jesus on every page to be highlighted.

My PHP code:

index: http://pastebin.com/vTdy79er
bible database: http://www.mediafire.com/?00x4fnbn1vr4nch

I have no idea how to go about doing this.

my select statement for my queries:

$searchResult = $dbLink->prepare("SELECT   bsect, bname, bnum, cnum, vnum, vtext,                                             MATCH    (bname, vtext)
AGAINST  ('$searchQuery' IN BOOLEAN MODE)
AS       relevance
FROM     kjv
WHERE    MATCH (bname, vtext)
AGAINST  ('$searchQuery' IN BOOLEAN MODE)
ORDER BY relevance
DESC
$limit"); 

The code that actually displays my results (bible name chapter number : verse number and then verse text:

while ($searchResult->fetch())
{
print ("<span class=\"results title\">$bname $cnum:$vnum</span>");
print ("<p class=\"passage\">$vtext</p>");
}

Upvotes: 0

Views: 498

Answers (3)

Fabrizio
Fabrizio

Reputation: 3776

I believe you already do it here:

$output = str_replace($_GET[phrase],"<font color=red>" . $_GET[phrase] . "</font>",$output);

even if I would suggest to change the code like this:

$output = str_replace($_GET['phrase'],'<font color="red">'.$_GET['phrase'].'</font>',$output);

or even better, use a <span> tag and a class, and then assign all the CSS that you want to that class and make it easier to change in the future

EDIT/ADD

with your last updated message, this is what you have to do (if I understand your code correctly)

print ("<p class=\"passage\">$vtext</p>");

change it to (assuming that $searchQuery is the variable that contain that string that is searched for

echo '<p class="passage">'.(str_replace($searchQuery, '<font color="red">'.$searchQuery.'</font>', $vtext).'</p>';

I also like better echo than print, but is personal preference. For sure you want to avoid the " and use the ' when possible as it will speed up PHP as the engine will not have to parse the whole string to find variables.. but again, personal preference

Upvotes: 1

str
str

Reputation: 44969

I did not look at your code but something like this should work:

echo str_replace($searchWord, '<span class="highlight">' . $searchWord . '</span>', $row['verse']);

Upvotes: 0

enloz
enloz

Reputation: 5824

Try this.

jQuery SearchHighlight plugin. Demo and implementation are provided.

Upvotes: 0

Related Questions