在富文本編輯、內容安全過濾等場景中,常需從 HTML 字符串中移除 <img> 標籤以防止圖片顯示或 XSS 風險。本文提供 Java 與 JavaScript 兩種語言的正則實現方案。
<script type="text/javascript">
var htmlContent = "<div id='test'><img src='aaa' height='4' width='4'></img><img src='ff' width='44' height='444' /></div>";
// 過濾 <img></img> 形式
var data = htmlContent.replace(/<img.*>.*<\/img>/ig, "");
// 過濾 <img /> 自閉合形式
data = data.replace(/<img.*\/>/ig, "");
alert(data); // 輸出: <div id='test'></div>
</script>
public class TestRegex {
public static void main(String[] args) {
String html = "<div id='test'><img src='aaa' height='4' width='4'></img><img src='ff' width='44' height='444' /></div>";
String destStr = html.replaceAll("<img.*>.*</img>", "")
.replaceAll("<img.*/>", "");
System.out.println(destStr); // 輸出: <div id='test'></div>
}
}
| 正則 | 匹配目標 | 說明 |
|---|---|---|
<img ...>...</img> | 貪婪匹配雙標籤形式,i 忽略大小寫,g 全局匹配 | |
<img ... /> | 匹配自閉合標籤 |
.* 會匹配盡可能多字符,若 HTML 中包含多個 img 標籤或巢狀結構,可能誤刪。建議使用非貪婪模式 .*?。> 字符,正則會失效。Jsoup、JS 的 DOMParser),按 DOM 樹操作移除節點,更安全可靠。String cleanHtml = Jsoup.parse(html)
.select("img").remove()
.html();
正則方案適合簡單、可控的場景快速原型;複雜或安全敏感場景請務必使用專業 HTML 解析器。