Option Explicit
Private Sub Command1_Click()
Dim sMyString As String
Dim sListArray() As String
Dim i As Long
' This just adds stuff to the listbox.
With List1
.AddItem "fry"
.AddItem "go"
.AddItem "gumballs"
.AddItem "hey"
.AddItem "mamma"
.AddItem "stick"
End With
' This creates an array of listbox items because the
' ReplaceWholeWords function needs an array of
' replacement words.
ReDim sListArray(List1.ListCount - 1)
For i = 0 To List1.ListCount - 1
sListArray(i) = List1.List(i)
Next
' This would be the text that you get in (well, maybe...)
sMyString = "Hey, sticky mamma! They are gonna go gobble " & _
"Mamma's gumballs, and fry Daddy's Fish-Stick"
' This shows the unaltered string
Text1.Text = sMyString
' Here we replace the "banned" words.
ReplaceWholeWords sMyString, sListArray
' This shows the "declassified" string.
Text2.Text = sMyString
End Sub
Function ReplaceWholeWords(ByRef Text As String, _
ByRef WordList() As String, _
Optional ByVal ReplaceChar As String = "*")
' Replaces whole words with the ReplaceCharacter.
' A whole word is considered to be any instance of the
' word that does not have a letter before or after it.
' Not case sensitive.
' Example: "Hello World!" with "world" in the
' word list and using default replacement character "*"
' returns "Hello *****!"
Dim sWord As String ' A word from the replace list.
Dim lWordLen As Long ' Length of the replace word.
Dim lWordStart As Long ' Start of the found word.
Dim lCharBefore As Long ' ASCII value of character before found word.
Dim lCharAfter As Long ' ASCII value of character after found word.
Dim i As Long ' Loop counter.
' Pad the string with spaces so that there is always
' a before and after character.
Text = " " & Text & " "
' Loop through the list of replacement words.
For i = 0 To UBound(WordList)
' Get replacement word, length of the word, and
' the start of the first instance of the word in
' the text string.
sWord = WordList(i)
lWordLen = Len(sWord)
lWordStart = InStr(1, Text, sWord, vbTextCompare)
' Check every instance of the found word.
Do Until lWordStart = 0
' Get ASCII value of characters before and
' after found word.
lCharBefore = Asc(UCase$(Mid$(Text, lWordStart - 1, 1)))
lCharAfter = Asc(UCase$(Mid$(Text, lWordStart + lWordLen, 1)))
' Check if characters before and after found word
' are letters. If there are no letter on either side
' the it is a "whole" word.
If (lCharBefore < 65 Or lCharBefore > 90) And _
(lCharAfter < 65 Or lCharBefore > 90) Then
' Repalce found whole word with replacement characters.
Mid$(Text, lWordStart, lWordLen) = String$(lWordLen, ReplaceChar)
End If
' Find start of next instance of word.
lWordStart = InStr(lWordStart + 1, Text, sWord, vbTextCompare)
Loop
Next
' Get rid of the padding that was added.
Text = Mid$(Text, 2, Len(Text) - 2)
End Function