Skip to main content
Inspiring
July 1, 2010
Question

highlight search term in search results

  • July 1, 2010
  • 1 reply
  • 859 views

HI folks,

I'd like to highlight the search term in my results page, somthing like below:

"It was popularised in the 1960s with the release of <span class="highlight">Letraset sheets</span>containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."

I'd like to include a set number of words either side of the occurance too, so the users gets a preview of the paragraph like in google.

Can anyone please tell me how to do this?

Many thanks

    This topic has been closed for replies.

    1 reply

    Inspiring
    July 1, 2010

    Check out CF's string functions.  I think you can accomplish this using the Replace function.  See sample below.

    <!--- note this code has not been tested --->
    <cfset searchTerm="Letraset sheets" />
    <cfset searchResults="It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum." />

    <cfoutput>#Replace(searchResults, searchTerm, '<span class="highlight">#searchTerm#</span>', 'ALL')# </cfoutput>

    Note that Replace function is case sensitive.  For a case-insensitive version use ReplaceNoCase.

    CF string functions:
    http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-6a3a.html