classic asp/vbscript - modify all hrefs with regex

China☆狼群 提交于 2019-12-11 02:25:39

问题


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


来源:https://stackoverflow.com/questions/39751644/classic-asp-vbscript-modify-all-hrefs-with-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!