Created
September 27, 2016 07:03
-
-
Save ivanionut/fe016427a0c81aefcf100dd046071f1b to your computer and use it in GitHub Desktop.
CFML: UDF to highlight keywords in a string (useful for search result pages)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<cfscript> | |
/* | |
I highlight words in a string that are found in a keyword list. Useful for search result pages. | |
@param str String to be searched | |
@param searchterm Comma delimited list of keywords | |
*/ | |
string function highlightKeywords( required string str, required string searchterm ){ | |
var j = ""; | |
var matches = ""; | |
var word = ""; | |
// loop through keywords | |
for( var i=1; i lte ListLen( arguments.searchterm, " " ); i=i+1 ){ | |
// get current keyword and escape any special regular expression characters | |
word = ReReplace( ListGetAt( arguments.searchterm, i, " " ), "\.|\^|\$|\*|\+|\?|\(|\)|\[|\]|\{|\}|\\", "" ); | |
// return matches for current keyword from string | |
matches = ReMatchNoCase( word, arguments.str ); | |
// remove duplicate matches (case sensitive) | |
matches = CreateObject( "java", "java.util.HashSet" ).init( matches ).toArray(); | |
// loop through matches | |
for( j=1; j <= ArrayLen( matches ); j=j+1 ){ | |
// where match exists in string highlight it | |
arguments.str = Replace( arguments.str, matches[ j ], "<span style='background:yellow;'>#matches[ j ]#</span>", "all" ); | |
} | |
} | |
return arguments.str; | |
} | |
</cfscript> | |
<cfoutput> | |
<h4>Before</h4> | |
<p>foo bar moo FOO BAR MOO</p> | |
<h4>After</h4> | |
<p>#highlightKeywords( "foo bar moo FOO BAR MOO", "foo bar" )#</p> | |
</cfoutput> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment