非常非常哈克(和真的不应该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
如果你想通过正则表达式来做到这一点(根据你的标签),记住这一点:规则1:不要使用RegEx来解析HTML。规则2:如果您仍想使用RegEx解析HTML,请参阅规则1. [RegEx只能匹配常规语言,而HTML不是常规语言](http://stackoverflow.com/a/590789/930393) – freefaller
@ freefaller看起来像你在那里与“为了上帝的爱,没有”建议在我面前。 :) –