VBScript preg_replace function

A VBScript equivalent of PHP’s preg_replace


Function preg_replace(pattern,replacement,ByVal subject,limit,ByRef cnt)

    Dim key
    cnt = 0

    If isArray(subject) Then
        For key = 0 to uBound(subject)
            subject(key) = preg_replace( pattern, replacement, subject(key),limit,cnt)
        Next
    ElseIf isObject(subject) Then
        For Each key In subject
            subject(key) = preg_replace( pattern, replacement, subject(key),limit,cnt)
        Next
    Else

        If isArray(pattern) Then
            If not isArray(replacement) Then
                For key = 0 to uBound(pattern)
                    subject = preg_replace( pattern(key), replacement, _
                                   subject,limit,cnt)
                Next
            ElseIf isArray(replacement) Then

                If uBound(pattern) <> uBound(replacement) Then
                    ReDim Preserve replacement(uBound(pattern))
                End If
                For key = 0 to uBound(pattern)
                    subject = preg_replace( pattern(key), replacement(key), _
                                   subject,limit,cnt)
                Next
            End If

        Else

            Dim strRetValue, RegEx,helper

            set helper = new RegExp_Helper
            helper.parseOption(pattern)

            Set RegEx = New RegExp
            With RegEx
                .IgnoreCase = helper.withIgnoreCase
                .Global     = [?](limit,false,true)
                .pattern    = helper.withPattern
                .MultiLine  = helper.withMultiLine
            End With
            set helper = Nothing

            If RegEx.Global Then
                If  len(subject) > 0 Then _
                subject = RegEx.Replace(subject, replacement)
            Else
                For key = 1 to limit
                    subject = RegEx.Replace(subject, replacement)
                    cnt = cnt + 1
                Next
            End If

            set RegEx = Nothing

        End If
    End If

    preg_replace = subject

End Function

Please also note that php.vbs offers community built functions and goes by the McDonald’s Theory. We’ll put online functions that are far from perfect, in the hopes to spark better contributions. Do you have one? Then please just:

Other PHP functions in the regexp extension