Highlighting search terms

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Calimero
Forum Contributor
Posts: 310
Joined: Thu Jan 22, 2004 6:54 pm
Location: Milky Way

Highlighting search terms

Post by Calimero »

If user inputs words into a textfield to search for,

What is the code for highlighting them in the results page?

Thanks Ahead!
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Here's an example you should be able to modify to suite:

Code: Select all

<?php
$results = 'one two three four five';
$search = 'three five six';
foreach(explode(' ', $search) as $word){
  $results = str_replace($word, '<span style="background-color:#f00">'.$word.'</span>', $results);
}
echo $results;
?>
Post Reply