使用者輸入的 HTML/UBB 內容若缺少結束標籤 (<div> 無 </div>),會導致版面崩潰。本文提供兩個函數:closehtml 處理常見 HTML 區塊標籤,closeUBB 處理論壇常用 UBB 標籤,原理皆為「計算開啟標籤數 - 結束標籤數 = 需補齊數量」,並在字串尾端補上對應結束標籤。
Function closehtml(strContent)
Dim arrTags, i, OpenPos, ClosePos, re, strMatchs, j, Match
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
' 需檢查的成對標籤 (不含自閉合標籤 img/br/hr/input 等)
arrTags = Array("p", "DIV", "span", "table", "ul", "font", "b", "u", "i", "h1", "h2", "h3", "h4", "h5", "h6")
For i = 0 To UBound(arrTags)
OpenPos = 0
ClosePos = 0
' 計算開啟標籤數: 或
re.Pattern = "<" & arrTags(i) & "([^<>]*)>"
Set strMatchs = re.Execute(strContent)
For Each Match In strMatchs: OpenPos = OpenPos + 1: Next
' 計算結束標籤數:
re.Pattern = "" & arrTags(i) & ">"
Set strMatchs = re.Execute(strContent)
For Each Match In strMatchs: ClosePos = ClosePos + 1: Next
' 補齊缺少的結束標籤
For j = 1 To OpenPos - ClosePos
strContent = strContent & "" & arrTags(i) & ">"
Next
Next
closehtml = strContent
Set re = Nothing
End Function
Function closeUBB(strContent)
Dim arrTags, i, OpenPos, ClosePos, re, strMatchs, j, Match
Set re = New RegExp
re.IgnoreCase = True
re.Global = True
arrTags = Array("code", "quote", "list", "color", "align", "font", "size", "b", "i", "u", "html")
For i = 0 To UBound(arrTags)
OpenPos = 0
ClosePos = 0
' 開啟標籤:[tag] 或 [tag=value]
re.Pattern = "\[" & arrTags(i) & "(=[^\]]*)?\]"
Set strMatchs = re.Execute(strContent)
For Each Match In strMatchs: OpenPos = OpenPos + 1: Next
' 結束標籤:[/tag]
re.Pattern = "\[/" & arrTags(i) & "\]"
Set strMatchs = re.Execute(strContent)
For Each Match In strMatchs: ClosePos = ClosePos + 1: Next
For j = 1 To OpenPos - ClosePos
strContent = strContent & "[/" & arrTags(i) & "]"
Next
Next
closeUBB = strContent
Set re = Nothing
End Function
Dim userInput
userInput = "粗體文字段落未閉合"
Response.Write closehtml(userInput)
' 輸出:
粗體文字段落未閉合
userInput = "[quote]引用內容[b]粗體未閉合"
Response.Write closeUBB(userInput)
' 輸出: [quote]引用內容[b]粗體未閉合[/b][/quote]
限制與注意
- **無法處理巢狀錯序**:如
<b><i>...</b></i> 仍會產生錯誤巢狀,瀏覽器會自動修正但不保證語意。
- **不處理屬性引號內的尖括號**:正則
[^<>]* 會誤判 <div title="a,實務建議用 HTML Parser (如 HTML Agility Pack 移植版) 或更嚴謹正則。
- **自閉合標籤** (
img, br, hr, input, meta, link) 不應納入檢查清單。
- 效能:長文本多次 RegExp.Execute 可能較慢,大量資料建議快取或移至客戶端處理。