PHP & MySQL | Tutorials

David Carr

Highlight matched words in a search

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.

function highlightWords($content, $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

$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

//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);



Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.