CFLib.org – Common Function Library Project

highlightKeywords(str, keywords, highlight)

Last updated September 29, 2012

author

Simon Bingham

Version: 1 | Requires: CF9 | Library: StrLib

Description:
Highlights words in a string that are found in a keyword list. Useful for search result pages.

Return Values:
Returns the string with the keywords highlighted.

Example:

<cfoutput>
<cfset l = "foo">
<cfset s = "foo zfooz foo foo zfoo fooz">
#l#<br />
#s#<br />
#highlightKeywords(s, l)#<br />
<hr />

<cfset l = "foo,bar">
<cfset s = "foo bar zfooz zbarz foo bar foo bar">
#l#<br />
#s#<br />
#highlightKeywords(s, l, {tag="span", attributes='style="color:red;"'})#<br />
<hr />

<cfset s = "fooz bar zfooz zbarz foo bar foo zbar">
#l#<br />
#s#<br />
#highlightKeywords(s, l, {tag="strong"})#<br />
<hr />
</cfoutput>

Parameters:

Name Description Required
str The string to highlight. Yes
keywords The list of keywords to highlight within the string. Yes
highlight A struct containing keys for tag and attributes, These are used to highlight the keyword. Defaults to an EM tag. Yes

Full UDF Source:

/**
 * Highlights words in a string that are found in a keyword list.
 * v0.9 by Simon Bingham.
 * v1.0 by Adam Cameron. Improved regex and added configurable highlighting.
 * 
 * @param str      The string to highlight. (Required)
 * @param keywords      The list of keywords to highlight within the string. (Required)
 * @param highlight      A struct containing keys for tag and attributes, These are used to highlight the keyword. Defaults to an EM tag. (Required)
 * @return Returns the string  with the keywords highlighted. 
 * @author Simon Bingham (me@simonbingham.me.uk) 
 * @version 1.0, September 29, 2012 
 */
string function highlightKeywords(required string str, required string keywords, struct highlight){
    var keyword        = "";
    var replacement    = "";
    
    param name="highlight.tag"            default="em";
    param name="highlight.attributes"    default="";
    
    for (var index=1; index <= listLen( arguments.keywords ); index++){
        keyword = listGetAt(arguments.keywords, index);
        replacement = "<#highlight.tag#";
        if (len(highlight.attributes)){
            replacement &= " #highlight.attributes#";
        }
        replacement &= ">" & keyword & "</#highlight.tag#>";

        arguments.str = reReplaceNoCase( arguments.str, "\b#keyword#\b", replacement, "all" );
    }
    return arguments.str;
}

Search CFLib.org


Latest Additions

Raymond Camden added
QueryDeleteRows
November 04, 2017

Leigh added
nullPad
May 11, 2016

Raymond Camden added
stripHTML
May 10, 2016

Kevin Cotton added
date2ExcelDate
May 05, 2016

Raymond Camden added
CapFirst
April 25, 2016

Created by Raymond Camden / Design by Justin Johnson