Strips all HTML tags from a string and replaces the tags with the specified replacement - CSharp System

CSharp examples for System:String HTML

Description

Strips all HTML tags from a string and replaces the tags with the specified replacement

Demo Code


using System.Web.Security;
using System.ComponentModel;
using System.Collections;
using System.Text.RegularExpressions;
using System.Text;
using System.Security.Cryptography;
using System.Reflection;
using System.Linq;
using System.Collections.Specialized;
using System.Collections.Generic;
using System;/* w  ww.  j a  v  a  2 s  . co m*/

public class Main{
        /// <summary>
        /// Strips all HTML tags from a string and replaces the tags with the specified replacement
        /// </summary>
        /// <param name="htmlString">The HTML string.</param>
        /// <param name="htmlPlaceHolder">The HTML place holder.</param>
        /// <returns></returns>
        public static string StripHTML(this string htmlString, string htmlPlaceHolder)
        {
            const string pattern = @"<(.|\n)*?>";
            string sOut = Regex.Replace(htmlString, pattern, htmlPlaceHolder);
            sOut = sOut.Replace("&nbsp;", String.Empty);
            sOut = sOut.Replace("&amp;", "&");
            sOut = sOut.Replace("&gt;", ">");
            sOut = sOut.Replace("&lt;", "<");
            return sOut;
        }
        /// <summary>
        /// Strips all HTML tags from a string
        /// </summary>
        /// <param name="htmlString">The HTML string.</param>
        /// <returns></returns>
        public static string StripHTML(this string htmlString)
        {
            return StripHTML(htmlString, String.Empty);
        }
}

Related Tutorials