Did you ever want to write a search engine similar to the big ones out there
that pull the keywords being searched on from the context of the document? In
this code snippet we're going to provide you with a method to search for a
string within a document, pull out the surrounding text, and then highlight that keyword within the
text being displayed.
We'll create a method called GetWrappingText. This method is going to accept
the following parameters:
- strSearchText: The text to be searched.
- strKeywords: What we're looking for within the text.
- intLength: How much of the surrounding text we want to pull.
Private Function GetWrappingText(ByVal strSearchText As _
String, ByVal strKeywords As String, ByVal intLength As Integer) As String
'declare our variables.
Dim tmpText As String = strSearchText
Dim tmpKeywords As String = strKeywords
Dim intKeywordPos As Integer
Dim intLimit As Integer = intLength
Dim strBefore As String
Dim strAfter As String
'our array to hold our keywords for searching.
Dim aryKeywords() As String
aryKeywords = tmpKeywords.Split(" ", 100) 'space delimiter
'see if there is a keyword in our text.
intKeywordPos = tmpText.ToLower.IndexOf(aryKeywords(0).ToLower)
Dim intLength1 As Integer
If intKeywordPos <> -1 Then 'found a keyword
'pull out the text before the keyword.
strBefore = tmpText.Substring(0, intKeywordPos)
If strBefore.Length > intLimit Then
intLength1 = strBefore.Length - intLimit
strBefore = strBefore.Remove(0, intLength1 - 1)
End If
intLength1 = intKeywordPos + aryKeywords(0).ToString.Length
Dim intLength2 As Integer
intLength2 = tmpText.Length
strAfter = tmpText.Substring(intLength1)
If strAfter.Length > intLimit Then
intLength1 = strAfter.Length - intLimit
strAfter = strAfter.Substring(0, intLimit)
End If
tmpText = strBefore & aryKeywords(0).ToString & strAfter
Dim j As Integer
'loop through each keyword and check to see if it is in the text.
Do While j <> aryKeywords.Length
If (aryKeywords(j).ToString.Trim.Length > 0) Then
'create a regular expression to insert the html bold tags.
Dim regex As regex = New regex(aryKeywords(j), RegexOptions.IgnoreCase)
Dim input As String = tmpText
Dim replacement As String = "<b>" + aryKeywords(j) & "</b>"
tmpText = regex.Replace(input, replacement)
End If
j = j + 1
Loop
tmpText = "..." & tmpText
End If
Return tmpText
End Function
So now if you're developing a search engine and someone types in some keywords like, the following would be displayed.
Here are the results of running a keyword search with hit
highlighting code applied to display the search text bolded.