Visual Basic 6 function "preg_replace"

Go back

Below you'll find the source for the Visual Basic 6 function preg_replace.

Attribute VB_Name = "modPregReplace"
' This function is downloaded from:
' http://www.stefanthoolen.nl/archive/vb6-functions/
' 
' You may freely distribute this file but please leave all comments, including this one, in it.
' 
' @Author Stefan Thoolen <mail@stefanthoolen.nl>

Option Explicit

''
' Perform a regular expression search and replace
' Same syntax as the PHP function 'preg_replace'
' See also: http://www.php.net/manual/en/function.preg-replace.php
' I only didn't copy limit and count because the MS VBScript library doesn't support them.
' Also only supports flags g(lobal), i(gnore case) and m(ultiline), and just a little bit of regexp patterns.
' Requires reference: Microsoft VBScript Regular Expressions 5.5 (vbscript.dll)
' @param    String  pattern     The perl regular expression
' @param    String  replacement The replacement for the regex
' @param    String  subject     The string to search in
' @return   String              The replaced string
' @author   Stefan Thoolen <mail@stefanthoolen.nl>
Public Function preg_replace(pattern As String, replacement As String, subject As String) As String
    Dim re As RegExp, i As Integer, flags As String, devider As String
    Set re = New RegExp
    devider = Left(pattern, 1)
    For i = Len(pattern) To 1 Step -1
        If Mid(pattern, i, 1) = devider Then Exit For
    Next i
    flags = Right(pattern, Len(pattern) - i)
    pattern = Mid(pattern, 2, i - 2)
    For i = 1 To Len(flags)
        If Mid(flags, i, 1) = "g" Then re.Global = True
        If Mid(flags, i, 1) = "i" Then re.IgnoreCase = True
        If Mid(flags, i, 1) = "m" Then re.MultiLine = True
    Next i
    re.pattern = pattern
    preg_replace = re.Replace(subject, replacement)
End Function