Jabooh web design Telford, Shropshire

Website design and IT solutions

Jabooh.com web design and IT solutions based in Telford Shropshire serving the Midlands and the whole of the UK.

Call us: 07530 259 181 or email us via the contact form for a free quote today.

Technologies we use: php, mysql, vb, google maps, database, content managed, cms, and javascript. Services we offer: search engine optimisation, hosting, website design, cheap websites.

Get in touch today if you are looking for an affordable website to help establish or improve your companies web presence.

The following php function will highlight a substring (or keyword) within another string, and is very useful for search results and displaying what a user searched for. The function wraps the keyword (if found) in a css class which can then be customised to quickly show the user the keyword in search results for example.

Usage: echo highlight('This is the input string, this is the keyword.','keyword');

Outputs: This is the input string, this is the keyword.

This function is on no way complete and if you notice any errors/improvements please let me know, I have found this function very useful and easy to use compared to some of the others out there that rely on regular expressions and dont take into account the case of the keyword.


    /**
    * highlight_keyword
    *
    * Highlight a keyword (needle) in searchstring (haystack) by adding a css class to the found word
    *
    * @param $haystack string The string to search within
    * @param $needle string The string to search for
    * @return string
    */ 
    
function highlight($haystack,$needle){
        
$match=strrpos(strtolower($haystack),strtolower($needle));
        if (
is_numeric($match)){
            
$len=strlen($needle);
            
$total mb_strlen($haystack);
            
$new_string_1="";
            
$new_string_2="<span class='keyword_highlight'>";
            for (
$k 0$k $total$k++) {
                
$char mb_substr($haystack$k1);
                if (
$k $match){
                    
$new_string_1.=$char;
                }elseif (
$k==($match $len)){
                    
$new_string_2.=$char "</span>";
                }else{
                    
$new_string_2.=$char;
                }
            }
            return 
$new_string_1 $new_string_2 "";
        }else{
            return 
$haystack;
        }        
    }

Are you looking for a website? Please get in touch

This page was last updated: 04 Jan 2012