過濾字符串中的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