2014-04-24 51 views
0

如何清理只留下纯文本和<a>元素的字符串?从asp.net中删除除<a>之外的html标记

例子:

<table><tr><td>Hello my web is <a href="http://www.myweb.com">Myweb</a>, <span>Follow my blog!</span></td></tr></table> 

结果:

Hello my web is <a href="http://www.myweb.com">Myweb</a>, Follow my blog! 

感谢,

+2

如果你想通过正则表达式来做到这一点(根据你的标签),记住这一点:规则1:不要使用RegEx来解析HTML。规则2:如果您仍想使用RegEx解析HTML,请参阅规则1. [RegEx只能匹配常规语言,而HTML不是常规语言](http://stackoverflow.com/a/590789/930393) – freefaller

+0

@ freefaller看起来像你在那里与“为了上帝的爱,没有”建议在我面前。 :) –

回答

2

非常非常哈克(和真的不应该productionally使用),但:

C#

Regex.Replace(input, @"<[^>]+?\/?>", m => { 
    // here you can exclude specific tags such as `<a>` or maybe `<b>`, etc. 
    return Regex.IsMatch(m.Value, @"^<a\b|\/a>$") ? m.Value : String.Empty; 
}); 

基本上,它只是需要出与<a ...>...</a>异常每个HTML代码。

注:这并不

  • 验证,如果标签被打开/关闭/嵌套正确。
  • 验证,如果<>实际上是HTML标签(也许你的输入在文本本身<>?)
  • 手柄“嵌套” <>标签。 (如<img src="http://placeholde.it/100" alt="foo<Bar>"/>会留下的"/>剩余输出字符串)

下面是变成一个辅助方法同样的事情:

// Mocks http://www.php.net/strip_tags 

/// <summary> 
/// Removed all HTML tags from the string and returned the purified result. 
/// If supplied, tags matching <paramref name="allowedTags"/> will be left untouched. 
/// </summary> 
/// <param name="input">The input string.</param> 
/// <param name="allowedTags">Tags to remain in the original input.</param> 
/// <returns>Transformed input string.</returns> 
static String StripTags(String input, params String[] allowedTags) 
{ 
    if (String.IsNullOrEmpty(input)) return input; 
    MatchEvaluator evaluator = m => String.Empty; 
    if (allowedTags != null && allowedTags.Length > 0) 
    { 
     Regex reAllowed = new Regex(String.Format(@"^<(?:{0})\b|\/(?:{0})>$", String.Join("|", allowedTags.Select(x => Regex.Escape(x)).ToArray()))); 
     evaluator = m => reAllowed.IsMatch(m.Value) ? m.Value : String.Empty; 
    } 
    return Regex.Replace(input, @"<[^>]+?\/?>", evaluator); 
} 

// StripTags(input) -- all tags are removed 
// StripTags(input, "a") -- all tags but <a> are removed 
// StripTags(input, new[]{ "a" }) -- same as above 
+0

比我的回答更好。 –

1

此代码将删除所有标签,但<a>标签。

 Regex r = new Regex(@"(?!</a>)(<\w+>|</\w+>)"); 
     var removedTags = r.Replace(inputString, ""); 
+0

仅供参考,您可以在'(?!'中压缩。但是你的正则表达式删除了'',我不相信它应该。 – Robin