VBScript preg_replace_callback function

A VBScript equivalent of PHP’s preg_replace_callback


Function preg_replace_callback(pattern,callback,ByVal subject,limit,ByRef cnt)

    Dim key,counter
    cnt = 0
    If len(limit) = 0 Then limit = 0

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

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

        Else

            Dim matchAll,strCallback
            If is_empty(limit) Then
                If preg_match_all(pattern, subject, matchAll,PREG_PATTERN_ORDER,") <> false Then
                    For Each key In matchAll(0)
                        execute("strCallback = " & callback & "(key)")
                        subject = Replace(subject,key,strCallback)
                    Next
                End If

            Else
                If preg_match_all(pattern, subject, matchAll,PREG_PATTERN_ORDER,") <> false Then
                    For Each counter In matchAll(0)
                        cnt = cnt + 1
                        If cnt > limit Then Exit For
                        execute("strCallback = " & callback & "(counter)")
                        subject = Replace(subject,counter,strCallback)
                    Next
                End If
            End If

        End If
    End If

    preg_replace_callback = 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