Highlight matched words in a search

David Carr

2 min read - 28th Jul, 2012

Table of Contents

This tutorial will show you how to highlight words from a search.

To learn how to search with php see Searching with PHP and MySQL beyond LIKE

First here is the function that will detect which words if any to highlight. The function expects 2 parameters
first the content and the words to search against.

A foreach loop is performed incase there is more then one search term, inside the loop a str_ireplace to replace each word from
search and wrap it in a span with a class to style the work with css then return the modified content.

<?php
function highlightWords($content, $search)
 {
    if(is_array($search)){
        foreach ( $search as $word )
        {
            $content = str_ireplace($word, '<span class="highlight_word">'.$word.'</span>', $content);
        }
    } else {
        $content = str_ireplace($search, '<span class="highlight_word">'.$search.'</span>', $content);        
    }
    return $content;
}
?>

Usage example

<?php
$search = 'program';
$content = 'He looked at their program and came to the conclusion that the best way for them to move forward';

echo highlightWords($content, $search);
?>

Search Example

<?php
//search data
$search = $_GET['search'];
$search = strip_tags($search);
$search = mysql_real_escape_string($search);

//check if search if not empty
if ($search =='') {
    echo "<div class='msg-error'>Opps! You forgot to enter a search word</div>n";
} else {    

        //perform the database search
        $q = mysql_query("SELECT * FROM table WHERE MATCH(pageConent) AGAINST('$search' IN BOOLEAN MODE)");
        $n = mysql_num_rows($q);
        if($n !=0){//there is a match

            //make search terms an array of terms
            $words = explode(" ",$search);
            while ($r = mysql_fetch_object($q))
            {
                //pass content to the function and print
                echo highlightWords($r->pageConent, $words);
            }

        }
}
?>

 

0 comments
Add a comment

Copyright © 2006 - 2024 DC Blog - All rights reserved.