La funzione Replace di Visual Basic 6.0 consente di sostituire qualunque occorrenza contenuta in una stringa di caratteri con un’altra stringa. La funzione è presente anche in VBScript ed è quindi utilizzabile in qualsiasi pagina ASP.
Chi usa Visual Basic 5 come può “simulare” la funzione Replace, introdotta con VB6, senza perdersi nei meandri delle istruzioni instr, mid, len e così via?
Ecco una funzione che chi possiede VB5 può usare con soddisfazione:
Public Function Replace(ByVal Expression As String, ByVal FindString As String, ByVal ReplaceString As String, _
Optional ByVal Start As Long = 1, Optional ByVal ReplaceCount As Long = -1, _
Optional ByVal Compare As VbCompareMethod = vbBinaryCompare) As String
'===================
' REPLACE FUNCTION
' Expression String to be searched.
' FindString String being sought.
' ReplaceString Replacement substring.
' Start Optional. Position within expression where substring
' search is to begin. If omitted, 1 is assumed.
' ReplaceCount Optional. Number of substring substitutions to perform.
' If omitted, the default value is 1, which means make
' all possible substitutions.
' Compare Optional. Numeric value indicating the kind of comparison
' to use when evaluating substrings. See Settings section
' for values.
'===================
Dim FindLen As Long ' length of search string
Dim pos As Long ' position where search string located
Dim nCount As Long ' # of replacements
On Error GoTo ErrHandler ' trap all errors
FindLen = Len(FindString) ' ID length of search string
pos = 1 ' initialize the loop
Do While pos > 0
pos = InStr(pos, Expression, FindString) ' locate search string
'Found, Is the string being replaced the same length as the search string
'If not I must divide the string at the search string position
If pos > 0 Then ' substring found
nCount = nCount + 1
Expression = Left$(Expression, pos - 1) & _
ReplaceString & _
Mid$(Expression, pos + FindLen) ' make the replacement
End If
If nCount = ReplaceCount Then Exit Do ' exit loop if max replacements reached
Loop
ExitLabel:
' Return the result
Replace = Expression
Exit Function
Resume
ErrHandler:
Debug.Print Err.Description: Debug.Assert 0
Resume ExitLabel
End Function
Invocando la funzione Replace nel modo seguente:
farete in modo che ogni occorrenza della stringa stringa_da_cercare contenuta in stringa venga sosituita da stringa_da_usare_per_la_sostituzione.