2011-07-19 35 views
0

我需要找到在HTML幾個HREF中是這樣的:替換vb.net asp.net HREF幾串

<table> 
<tr><td><a href="url1">link1</a></td> 
<td><a href="url2"><img src="image.jpg" /></a></td> 
</tr> 
</table> 

一旦發現我需要(替換)添加到每個HREF是這樣的:

?ID=1 

因此HTML應該會是這樣:

<table> 
<tr><td><a href="url1?ID=1">link1</a></td> 
<td><a href="url2?ID=1"><img src="image.jpg" /></a></td> 
</tr> 
</table> 

任何幫助,將不勝感激,謝謝,邁克。

回答

0

這裏的新代碼:

Shared Function AdjustURL(ByVal psInput As String, ByVal psAppend As String) As String 
    Dim sOrig As String = " " & psInput 'Prepending a space (browser will ignore) in case the first character is a link. 
    Dim sOutput As String = "" 
    Dim iEnd As Integer = -1, iQuestion As Integer = -1 

    While sOrig.Length > 0 
     sOutput &= sOrig.Substring(0, 1) 
     sOrig = sOrig.Substring(1) 
     iEnd = -1    
     If sOrig.StartsWith("<a href=") Then 'Is this a safe assumption, what if it's not an <a> or href isn't next after only one space? 
      If sOrig.StartsWith("<a href=""") Then 
       iEnd = InStr(10, sOrig, """") 'URL ends with a Quote 
      Else 
       iEnd = InStr(9, sOrig, " ") 'URL ends with a Space - are there other possibilities? 
      End If 
      iQuestion = InStr(sOrig, "?") 
      If iQuestion > iEnd Then iQuestion = -1 
      sOutput &= sOrig.Substring(0, iEnd - 1) & IIf(iQuestion > -1, "?", "&") & psAppend 
      sOrig = sOrig.Substring(iEnd - 1) 
     End If 
    End While 
    Return sOutput 

End Function 

電話:

Dim sHTML As String = "<table> <tr><td><a href=""url1"">link1</a></td> <td><a href=""url2""><img src=""image.jpg"" /></a></td> </tr> </table>" 
Response.Write(Class1.AdjustURL(sHTML, "ID=1")) 

結果:

<table> <tr><td><a href="url1?ID=1">link1</a></td> <td><a href="url2?ID=1"><img src="image.jpg" /></a></td> </tr> </table> 

我肯定會有其他的替代品,你會發現隨着時間的推移,因爲用戶輸入東西。我肯定會推薦用<span style=display:none之類的東西替換<script以避免JavaScript注入。在將其寫入數據庫之前,您還需要確保避免SQL注入。

+0

感謝您的快速回復,但恐怕不是那麼簡單,因爲我不知道href的價值! (第二)找到所有以href開頭(以「」結尾)的字符串(example = href =「url1」),(3rd)改變它們,(第四)放入他們回到原地(例如= href =「url1」變爲href =「url1?ID = 1」)。 但我喜歡我上面說過:我不知道用戶插入爲Href。 Mike – Mike

+0

在最後一塊代碼中,它建議連接另一個綁定,但您可以確定連接「?ID =」和請求(「targetid」)。ToString ...或ddlValue.selectedValue或任何您想要獲取數據 - 雖然我會建議在使用它之前對值進行消毒。 根據你的評論,它看起來像你有興趣把整個頁面作爲一個字符串並做替換。您可以將渲染事件捕獲到一個字符串中並進行必要的替換。 這種事情在經典的ASP中很棒,但現在,jQuery可能是更好的選擇。 –

+0

是的,整個Html必須被視爲一個。 這實際上並不是關於Page Html,而是由用戶將其插入到數據庫中並將其作爲新聞稿發送時更新。 當通訊發送時,必須將幾個QueryStrings添加到每個單獨的hrefs中。 我不使用jQuery,也許你可以給我提供一些幫助,以舊的方式:)。 – Mike