在Razor MVC 3中删除HTML格式化

6
我正在使用MVC 3和Razor View引擎。
我正在使用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>", " ");
 }

我感觉一定有更好的方法来解决这个问题。能否请有经验的人指导一下。


1
请参阅 https://dev59.com/J3RA5IYBdhLWcg3w6SNH 获取更多信息,或使用 Html Agility Pack 进行删除。 - Alex Yaroshevich
3个回答

23

感谢 Alex Yaroshevich

这是我目前使用的代码:

post.PostContent = Regex.Replace(post.PostContent, @"<[^>]*>", String.Empty);

2
正则表达式速度较慢。使用这个,它更快:
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

这不会去除 标签。 - David C

0

如果你想在.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);

我并不是说这是最好的答案。这只是一个选项,对我来说效果很好。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接