Today, there is a question: How to highlight case-insensitive keywords in a Web page
For example: text abcabcabcabcabcabca, keyword BC, in case of case-insensitive, a total of 6 matches.
The ABCABCABCABCABCABCA is displayed in the Web page.
Many people think of the replace function. Prototype for
Replace (String,find,replacewith[,start[,count[,compare]]])
String must be an expression that contains the substring to be substituted
Find must option, substring searched
ReplaceWith required, substring to replace
Start option to begin searching for the location of the substring, default is 1
Count is optional, the number of substring substitutions is performed, and the default is-1, which means that all possible substitutions are made
Compare options, Comparison mode, 0: binary comparison; 1: text comparison
Although the last argument solves a case-insensitive problem, what is the replacement?
Because from the example, BC,BC,BC,BC is searched, but cannot be replaced uniformly with one text
So, use the InStr function to help us.
From the source string, search from left to right, each match found. Just follow the three steps.
1, the string to the left of the match output
2, the match will be nested style <span> after output
3, repeat the previous two steps, continue to search the right string until the end of the search
The code is as 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
When called, the code is as follows:
Ts= "ABCABCABCABCABCABCA"
tf= "BC"
Response. Write (TS)
Response. Write ("<br/>")
Response. Write (Highlight (TS,TF))
This makes it look like the beginning instance.
On the other hand, is it more convenient to think of regular expressions? Tried a few times, no results. See which Master uses the regular to solve this problem.
After writing the article, the Netizen "Yu Gong" gave the regular expression solution. Tested and correct. Now put his code on the post. Thank him 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& Lt;/span> ")
End Function
Response.Write Highlight (" ABCABCABCABCABCABCA "," BC ")