How can I strip HTML tags from a string in ASP.NET

2019-01-01 05:05发布

Using ASP.NET, how can I strip the HTML tags from a given string reliably (i.e. not using regex)? I am looking for something like PHP's strip_tags.

Example:

<ul><li>Hello</li></ul>

Output:

"Hello"

I am trying not to reinvent the wheel, but I have not found anything that meets my needs so far.

13条回答
柔情千种
2楼-- · 2019-01-01 05:55

I've posted this on the asp.net forums, and it still seems to be one of the easiest solutions out there. I won't guarantee it's the fastest or most efficient, but it's pretty reliable. In .NET you can use the HTML Web Control objects themselves. All you really need to do is insert your string into a temporary HTML object such as a DIV, then use the built-in 'InnerText' to grab all text that is not contained within tags. See below for a simple C# example:


System.Web.UI.HtmlControls.HtmlGenericControl htmlDiv = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
htmlDiv.InnerHtml = htmlString;
String plainText = htmlDiv.InnerText;
查看更多
登录 后发表回答