分享

正则表达式过滤Html标签

 二宝么么哒 2010-12-27
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text.RegularExpressions;
/// <summary>
/// Filter 的摘要说明
/// </summary>
public class FilterHtmlCode
{
    /// <summary>
    /// 过滤HTML标签
    /// </summary>
    public FilterHtmlCode()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }

    public static string NoHtml(string text)
    {
        //删除脚本
        text = Regex.Replace(text, @"<script[^>]*?>.*?</script>", "", RegexOptions.IgnoreCase);
        //删除HTML
        text = Regex.Replace(text, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"([\r\n])[\s]+", "", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"-->", "", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"<!--.*", "", RegexOptions.IgnoreCase);

        text = Regex.Replace(text, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(nbsp|#160);", " ", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
        text = Regex.Replace(text, @"&#(\d+);", "", RegexOptions.IgnoreCase);
        text.Replace("<", "");
        text.Replace(">", "");
        text.Replace("\r\n", "");
        text = HttpContext.Current.Server.HtmlEncode(text).Trim();
        return text;
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约