C#中,我們有時需要過濾掉字符串中的部分html標簽,以下是一些簡單的html標簽過濾方法,使用的主要方式是正則表達式
public static string ClearHtml(string html) { if(string.IsNullOrEmpty(html)) { return ""; } //去除a標簽 html = Regex.Replace(html, @"<a\s*[^>]*>", "", RegexOptions.IgnoreCase); html = Regex.Replace(html, @"</a>", "", RegexOptions.IgnoreCase); //去除span標簽 html = Regex.Replace(html, @"<span\s*[^>]*>", "", RegexOptions.IgnoreCase); html = Regex.Replace(html, @"</span>", "", RegexOptions.IgnoreCase); //去除所有的樣式 html = Regex.Replace(html, @"\sstyle=""([^"";]+;?)+""", "", RegexOptions.IgnoreCase); //去除所有的html標簽 html = Regex.Replace(html, @"<[^>]*>| ", "", RegexOptions.IgnoreCase); return html; }