Highlight matched words in a search

David Carr

PHP & MySQL Tutorials

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

        }
}
?>

 

Fathom Analytics $10 discount on your first invoice using this link

David Carr - Laravel Developer

Hi, I’m David Carr

A Senior Developer at Vivedia
I love to use the TALL stack (Tailwind CSS, Alpine.js, Laravel, and Laravel Livewire)

I enjoy writing tutorials and working on Open Source packages.

I also write books. I'm writing a new book Laravel Testing Cookbook, This book focuses on testing coving both PestPHP and PHPUnit.

Sponsor me on GitHub

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Laravel Testing Cookbook

Help support the blog so that I can continue creating new content!

Fathom Analytics $10 discount on your first invoice using this link

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2006 - 2023 DC Blog. All code MIT license. All rights reserved.