classic asp/vbscript - modify all hrefs with regex

2019-07-21 06:19发布

问题:

In Classic ASP (VB Script), I need to modify multiple distinct hrefs that are contained in a string by encoding the current url and pre-pending to it.

Basically, I want to make all hrefs go through my redirect.asp and pass in the existing href encoded into the new link.

For example:

existing:

<a href="http://www.dairyqueen.com/us-en/Promotions-US/?localechange=1&test=1">

desired result:

<a href="/redirect.asp?id=123&url=http%3A%2F%2Fwww.dairyqueen.com%2Fus-en%2FPromotions-US%2F%3Flocalechange%3D1%26test%3D1">

Note that there are multiple distinct href contained in the string. All of them need to be replaced.

In addition, I would also like to add an additional attributes within the href as well, which I probably could do just using a replace(myString,"<a href","<a target=""_blank"" href=") unless there is a better way.

optimal result:

<a target="_blank" href="/redirect.asp?id=123&url=http%3A%2F%2Fwww.dairyqueen.com%2Fus-en%2FPromotions-US%2F%3Flocalechange%3D1%26test%3D1">

回答1:

Take a look at the below code:

' <a href="http://www.dairyqueen.com/us-en/Promotions-US/?localechange=1&test=1">
sHtml = "<a href=""http://www.dairyqueen.com/us-en/Promotions-US/?localechange=1&test=1"">"

Set refRepl = GetRef("fnRepl")
With CreateObject("VBScript.RegExp")
    .Global = True
    .MultiLine = True
    .IgnoreCase = True
    .Pattern = "<a([\s\S]*?)href=""([\s\S]*?)""([\s\S]*?)>"
    sResult = .Replace(sHtml, refRepl)
End With

' <a target="_blank" href="/redirect.asp?id=123&url=http%3A%2F%2Fwww.dairyqueen.com%2Fus-en%2FPromotions-US%2F%3Flocalechange%3D1%26test%3D1">
MsgBox sResult

Function fnRepl(sMatch, sSubMatch1, sSubMatch2, sSubMatch3, lPos, sSource)
    fnRepl = "<a" & sSubMatch1 & "target=""_blank"" href=""/redirect.asp?id=123&url=" & EncodeUriComponent(sSubMatch2) & """" & sSubMatch3 & ">"
End Function

Function EncodeUriComponent(sText)
    With CreateObject("htmlfile")
        .ParentWindow.ExecScript (";")
        EncodeUriComponent = .ParentWindow.EncodeUriComponent(sText)
    End With
End Function