ここでは文字列操作が必要です..私は正規表現にあまり興味がなかったので、ずっと前にさまざまな方法でテキストを操作するための独自のメソッドをたくさん用意しました。かなり醜く、最高の効率ではありませんが、機能します。
まず、これらの関数をコードに追加します。
Function GetBetween(str, leftDelimeter, rightDelimeter)
Dim tmpArr, result(), x
tmpArr=Split(str, leftDelimeter)
If UBound(tmpArr) < 1 Then
GetBetween=Array() : Exit Function
End If
ReDim result(UBound(tmpArr)-1)
For x=1 To UBound(tmpArr)
result(x-1)=(Split(tmpArr(x), rightDelimeter))(0)
Next
Erase tmpArr
GetBetween=result
End Function
Function ReplaceWholeWord(ByVal strText, strWord, strToReplaceWith)
ReplaceWholeWord = strText
If InStr(strText, strWord)<1 Then Exit Function
'Text is only the word?
If strText=strWord Then
strText = Replace(strText, strWord, strToReplaceWith)
Else
'Text starting with word?
If InStr(strText, strWord & " ")=1 Then
strText = strToReplaceWith & " " & Right(strText, Len(strText) - Len(strWord & " "))
End If
'Text ends with word?
If Right(strText, Len(" " & strWord))=(" " & strWord) Then
strText = Left(strText, Len(strText) - Len(" " & strWord)) & " " & strToReplaceWith
End If
'Text ends with word and a period?
If Right(strText, Len(" " & strWord & "."))=(" " & strWord & ".") Then
strText = Left(strText, Len(strText) - Len(" " & strWord & ".")) & " " & strToReplaceWith & "."
End If
'Replace between other words:
strText = Replace(strText, " " & strWord & " ", " " & strToReplaceWith & " ")
End If
ReplaceWholeWord = strText
End Function
これらの関数を使用して、必要な方法でキーワードを置き換えるサンプル コードを次に示します。
Const KEYWORD = "keyword"
Dim strHTML, arrTagsToFind, x
Dim curItemsArray, y, curItem
Dim curReplacedItem
arrTagsToFind = Array("p", "div")
strHTML = "<b>this keyword will not be replaced</b><p>Some text with the keyword.</p>keyword here won't be replaced too<p>Some other text with the keyword22 that is not whole word but end with keyword</p><div>keyword first</div>"
For x=0 To UBound(arrTagsToFind)
curItemsArray = GetBetween(strHTML, "<" + arrTagsToFind(x) + ">", "</" + arrTagsToFind(x) + ">")
For y=0 To UBound(curItemsArray)
curItem = curItemsArray(y)
curReplacedItem = ReplaceWholeWord(curItem, KEYWORD, "<a href=""#foo"">" & KEYWORD & "</a>")
strHTML = Replace(strHTML, curItem, curReplacedItem)
Next
Next
Response.Write(strHTML)