过滤字符串中的html标签


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, @"<[^>]*>|&nbsp;", "", RegexOptions.IgnoreCase);
            return html;
        }


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM