如何从ASP.NET中的一个字符串中去除HTML标签? [英] How can I strip HTML tags from a string in ASP.NET?

查看:230
本文介绍了如何从ASP.NET中的一个字符串中去除HTML标签?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ASP.NET,我怎么能剥去可靠特定字符串的HTML标记(即不使用正则表达式)?我在寻找类似PHP的用strip_tags

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.

< UL><李>你好< /李>< / UL>

你好

我想不是推倒重来,但我还没有发现任何东西,符合我的需要为止。

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

推荐答案

如果是刚剥的所有的字符串中的HTML标签,这与正则表达式可靠地工作为好。替换:

If it is just stripping all HTML tags from a string, this works reliably with regex as well. Replace:

<[^>]*(>|$)

与空字符串,在全球范围。不要忘了事后正常化的字符串,替换:

with the empty string, globally. Don't forget to normalize the string afterwards, replacing:

[\s\r\n]+

用一个空格,和修整的结果。可选择更换任何HTML字符实体回的实际字符。

with a single space, and trimming the result. Optionally replace any HTML character entities back to the actual characters.

注意


  1. 有一个限制:HTML和XML允许&GT; 属性值。该解决方案的将会的遇到这样值时,回破的标记。

  2. 解决方案在技术上是安全的,如:结果永远不会包含任何可能被用来做跨站点脚本或打破页面布局。这只是不是很干净。

  3. 正如所有的事情HTML和正则表达式:结果
    使用一个适当的解析器如果你一定要得到它在任何情况下正确的。

  1. There is a limitation: HTML and XML allow > in attribute values. This solution will return broken markup when encountering such values.
  2. The solution is technically safe, as in: The result will never contain anything that could be used to do cross site scripting or to break a page layout. It is just not very clean.
  3. As with all things HTML and regex:
    Use a proper parser if you must get it right under all circumstances.

这篇关于如何从ASP.NET中的一个字符串中去除HTML标签?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆