String question: Returning portion of string with words surrounding highlighted search term?

String question: Returning portion of string with words surrounding highlighted search term?

Post by Ken Fin » Fri, 15 Aug 2003 01:19:04


I'm looking to find or create an ASP script that will take a string, examine
it for a search term, and if it finds the search term in the string, return
the highlighted search term along with the words that surround it. In other
words, I want the search term highlighted and shown in an excerpt of the
context in which it appears.

Any suggestions or pointers? This behavior is most often seen as part of a
search engine. In my case, I want to use it as part of a content "scanner"
that utilizes a screen scraping component.
 
 
 

String question: Returning portion of string with words surrounding highlighted search term?

Post by Ken Fin » Fri, 15 Aug 2003 04:21:54

The hard part of this problem isn't highlighting the search term, which has
been done a million times before, but rather pulling out, say, 300
characters that precede the search term and 300 characters that follow it,
so that I can show the context that a term appeared in.





a
"scanner"
#FF0000"">"
you

 
 
 

String question: Returning portion of string with words surrounding highlighted search term?

Post by Alan » Fri, 15 Aug 2003 08:41:57

This will get you started:

Dim Pos
Dim Extract
Const BufferLen = 300

Pos = InStr (1, SourceString, SearchTerm, vbTextCompare)

If (Pos<>0) Then

' Search term found.
Extract = Mid(SourceString, Pos - BufferLen, ((2*BufferLen) +
Len(SearchTerm)))

End If

It'll need some tweaking and I haven't tested it. Make sure you don't read
past either end of SourceString. I'd be a bit worried about the efficiency
of this if you're doing it multiple times on a page - you'll have to
optimise it by storing the Pos of the last hit and starting from that
position for your next iteration. Perhpas something like this (untested):

Pos = InStr (1, SourceString, SearchTerm, vbTextCompare)
Do While Pos <> 0

' Get the extract.
Extract = Mid(SourceString, Pos - BufferLen, ((2*BufferLen) +
Len(SearchTerm)))
' Next Pos.
Pos = InStr (Pos, SourceString, SearchTerm, vbTextCompare)

Loop

Try that.

Alan



has




the
of