PDA

View Full Version : Highlighting searched keywords



junestag
07-25-2008, 03:38 PM
Hello,
I'm wondering if this is possible: when my users search in a free text box and results are returned in php/mysql...is it possible to somehow highlight the words they searched for in the returned records?

thanks,
sage

benslayton
07-25-2008, 09:45 PM
Well I can say that I have never done this but, the first thing that came to my mind was this...


<?php
//Get the search string... search.php?q=content
$q = $_REQUEST['q'];

$content = "This is all of your content from your mysql database. Get it here however";


//Highlight the keywords
$updatedContent = str_replace($q, "<span style=\"background-color:yellow\">" . $q . "</span>", $content);

echo $updatedContent;

?>

Maybe someone else knows of a better way of doing this... But ive never done search scripts, but the concept above would work...

thetestingsite
07-26-2008, 12:43 AM
Instead of using this line:



$updatedContent = str_replace($q, "<span style=\"background-color:yellow\">" . $q . "</span>", $content);


try using this instead so that the search is case-insensitive:



$updatedContent = str_ireplace($q, "<span style=\"background-color:yellow\">" . $q . "</span>", $content);


Hope this helps

benslayton
07-26-2008, 02:19 AM
Good thinking testing... That didnt even dawn on me...

JsusSalv
09-28-2008, 02:11 AM
Hello:

I just used str_ireplace for a search script but came across an issue. Here's my code:


str_ireplace($var, '<span class="highlight_pink">'.$var.'</span>', $FirstName);

The problem I'm seeing is that when I search for the word 'solar' and there are records in the database that match the result set changes the case of the word. So 'SOLAR' or 'Solar' is displayed on screen as 'solar.' I'd like to keep the case of the database record and not change it to whatever was put into the search field.

Any ideas on what to do?

Thanks!

Master_script_maker
09-28-2008, 05:39 PM
try
preg_replace('/('.$var.')/i', '<span class="highlight_pink">$1</span>', $FirstName);

JsusSalv
09-28-2008, 09:12 PM
Thank you Master Script Maker!!! That worked beautifully!

Master_script_maker
09-29-2008, 12:30 AM
Your welcome! There's a button for thanks too :p.