我使用MVC 3 Razor视图引擎。
我所试图做的
我正在使用MVC 3一个博客,我想删除像所有的HTML格式标记<p> <b> <i>
等。
为此我使用下面的代码。 (它的工作)
@{
post.PostContent = post.PostContent.Replace("<p>", " ");
post.PostContent = post.PostContent.Replace("</p>", " ");
post.PostContent = post.PostContent.Replace("<b>", " ");
post.PostContent = post.PostContent.Replace("</b>", " ");
post.PostContent = post.PostContent.Replace("<i>", " ");
post.PostContent = post.PostContent.Replace("</i>", " ");
}
我觉得有绝对有更好的方法来做到这一点。 任何人都可以请指导我在此。
感谢亚历克斯亚罗舍维奇,
以下是我现在用的..
post.PostContent = Regex.Replace(post.PostContent, @"<[^>]*>", String.Empty);
正则表达式是缓慢的。 利用这一点,它的速度更快:
public static string StripHtmlTagByCharArray(string htmlString)
{
char[] array = new char[htmlString.Length];
int arrayIndex = 0;
bool inside = false;
for (int i = 0; i < htmlString.Length; i++)
{
char let = htmlString[i];
if (let == '<')
{
inside = true;
continue;
}
if (let == '>')
{
inside = false;
continue;
}
if (!inside)
{
array[arrayIndex] = let;
arrayIndex++;
}
}
return new string(array, 0, arrayIndex);
}
你可以看看http://www.dotnetperls.com/remove-html-tags
万一你想使用正则表达式在.NET中剥离HTML标签,下面似乎在源代码中工作得很好出于这个页面。 这比一些此页面上的其他答案的更好,因为它会查找实际的HTML标签,而不是盲目地去除之间的一切<
和>
。 早在BBS里,我们键入<grin>
很多,而不是:)
,所以删除<grin>
是不是一种选择。 :)
该解决方案只删除标签。 它不会删除这些标签的内容的情况下,可能是重要的 - 一个脚本标记,例如。 你会看到剧本,但因为脚本标记本身被删除脚本将无法执行。 删除HTML标记的内容是非常棘手的,切实需要的HTML片段很好地形成...
还要注意RegexOption.Singleline
选项。 这对于任何HTML块非常重要。 因为没有什么错在一行中打开HTML代码,并在另一关闭它。
string strRegex = @"</{0,1}(!DOCTYPE|a|abbr|acronym|address|applet|area|article|aside|audio|b|base|basefont|bdi|bdo|big|blockquote|body|br|button|canvas|caption|center|cite|code|col|colgroup|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frame|frameset|h1|h2|h3|h4|h5|h6|head|header|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|menu|menuitem|meta|meter|nav|noframes|noscript|object|ol|optgroup|option|output|p|param|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video|wbr){1}(\s*/{0,1}>|\s+.*?/{0,1}>)";
Regex myRegex = new Regex(strRegex, RegexOptions.Singleline);
string strTargetString = @"<p>Hello, World</p>";
string strReplace = @"";
return myRegex.Replace(strTargetString, strReplace);
我并不是说这是最好的答案。 这只是一个选项,这对我来说真是棒极了。