经典的asp / vbscript - 使用正则表达式

时间:2016-09-28 15:23:18

标签: regex replace vbscript asp-classic

在Classic ASP(VB Script)中,我需要通过编码当前url并预先挂起来修改字符串中包含的多个不同的href。

基本上,我想让所有href通过我的redirect.asp并将现有的href编码传递给新链接。

例如:

现有

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

期望的结果:

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

请注意,字符串中包含多个不同的href。所有这些都需要更换。

此外,我还想在href中添加一个额外的属性,除非有更好的方法,否则我可能只使用replace(myString,"<a href","<a target=""_blank"" href=")

最佳结果:

<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 个答案:

答案 0 :(得分:1)

看看下面的代码:

' <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