VBScript substr_count function

A VBScript equivalent of PHP’s substr_count


Function substr_count( haystack, needle, offset, length )

    Dim pos,cnt : cnt = 0

    If not isNumeric(offset) Then offset = 1
    If not isNumeric(length) Then length = 0

    Do While inStr(offset+1,haystack,needle,vbBinaryCompare) > 0
        offset = inStr(offset+1,haystack,needle,vbBinaryCompare)
        If length > 0 and offset + len(needle) > length Then
            Exit Do
        Else
            cnt = cnt + 1
        End If
    Loop

    substr_count = cnt

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 strings extension