本文實例講述了C#正則過濾HTML標簽并保留指定標簽的方法。分享給大家供大家參考,具體如下:
這邊主要看到一個過濾的功能:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
public static string FilterHtmlTag( string s) { //<...>標記正則表達式 return Regex.Replace(s, @"<[^>]*>" , delegate (Match match) { string v = match.ToString(); //圖片,<p>,<br>正則表達式 Regex rx = new Regex( @"^<(p|br|img.*)>$" , RegexOptions.Compiled | RegexOptions.IgnoreCase); // if (rx.IsMatch(v)) { return v; //保留圖片,<p>,<br> } else { return "" ; //過濾掉 } }); } |
我這邊所有都過濾,所以我直接用正則,不再做匿名委托的保留p和br
1
2
3
|
content = Regex.Replace(content, @"/\<span(\sclass\=\S*)*\>\S*\<\/span\>/g" , "" , RegexOptions.IgnoreCase); content = Regex.Replace(content, @"<[^>]*>" , "" , RegexOptions.IgnoreCase); content = content + "。。。" ; |
希望本文所述對大家C#程序設計有所幫助。