Today, I encountered a problem: how to highlight case-insensitive keywords on a webpage
For example, for text abcabcabcabcabcabcabca, the keyword BC, there are 6 matching items in case of case insensitive.
A is displayed on the webpage.BCABCABCABCABCABCA.
Many people think of the replace function. Prototype:
Replace (string, find, replacewith [, start [, Count [, compare])
String mandatory, string expression, including the substring to be replaced
Find (required): The substring to be searched.
Replacewith: A required substring to be replaced.
Start: Optional. Start to search for the position of the substring. The default value is 1.
Count option. The number of substrings to replace. The default value is-1, indicating all possible replications.
Compare option, comparison method, 0: Binary comparison; 1: text comparison
Although the last parameter can solve the case-insensitive problem, why should it be replaced?
In this example, BC, and BC are all searched, but cannot be replaced with a single text.
Use the instr function to help us.
Search from the source string, left to right, and each matching item is found. Take three steps
1. output the string on the left of the matching item
2. Set the matching item to the style <span> and output it.
3. Repeat the previous two steps to continue searching for the string on the right until the end of the search.
CodeAs follows:
Public Function Highlight (S, F)
Dim TL, TM, TR, K
TL = ""
TM = ""
Tr = S
K = Instr ( 1 , TR, F, 1 )
Do While K > 0
TL = TL & Left (TR, K - 1 )
TM = Mid (TR, K, Len (F ))
TL = TL & " <Span style = 'color: red'> " & TM & " </Span> "
Tr = Right (TR, Len (TR) - Len (F) - K + 1 )
K = Instr ( 1 , TR, F, 1 )
Loop
Highlight = TL & Tr
End Function
The Code is as follows:
TS = " Abcabcabcabcabcabca "
TF = " BC "
Response. Write (TS)
Response. Write ( " <Br/> " )
Response. Write (highlight (TS, TF ))
In this way, the starting instance is implemented.
On the other hand, is it more convenient to use regular expressions? Failed after several attempts. Let's see which expert uses regular expressions to solve this problem.
WrittenArticleLater, the netizen "yugong" gave a solution to the regular expression. The test result is correct. Now he posts his code to the back. Thank you very much.
Code
Function Highlight (S, F)
Dim RegEx
Set RegEx = New Regexp
RegEx. ignorecase = True
RegEx. Global = True
RegEx. Pattern = " ( " & F & " ) "
Highlight = RegEx. Replace (S, " <Span style = 'color: red'> $1 </span> " )
End Function
Response. Write highlight ( " Abcabcabcabcabcabca " , " BC " )