C# ASP.NET 移除html标签, 过滤html标签
using System;
using System.Text.RegularExpressions;
namespace ConsoleApp29
{
class Program
{
static void Main(string[] args)
{
string html = "<a href=\"http://localhost\" />移除html标签<a>";
Console.WriteLine(html);
Console.WriteLine(RemoveHtml(html));
Console.Read();
}
/// <summary>
/// Remove HTML tags
/// </summary>
/// <param name="input">input</param>
/// <returns></returns>
static string RemoveHtml(string input)
{
if (string.IsNullOrEmpty(input)) { return ""; }
// 1
input = Regex.Replace(input, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"&#(\d+);", "", RegexOptions.IgnoreCase);
// 2
input = Regex.Replace(input, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"-->", "", RegexOptions.IgnoreCase);
input = Regex.Replace(input, @"<!--.*", "", RegexOptions.IgnoreCase);
return input;
}
}
}