首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ASP.NET正在尝试从字符串中剥离html

ASP.NET正在尝试从字符串中剥离html
EN

Stack Overflow用户
提问于 2011-05-27 23:45:21
回答 4查看 1.3K关注 0票数 1

所以我有一个cms,用户可以通过cuteeditor输入内容,它工作得很好,然后在我的网站上显示这些数据。有一件事很少发生,但令人恼火,那就是用户在他们的文本中输入某些标记,这会使字体看起来与页面上的其他字体不同。

代码语言:javascript
复制
<span style="font-size: 11pt">Special Olympics Ireland provides year round sports training and athletic competition&nbsp;in a variety of Olympic&nbsp;type sports&nbsp;for persons with&nbsp;intellectual&nbsp;disabilities&nbsp;in </span><span style="font-size: 11pt">Ireland</span><span style="font-size: 11pt"> and </span><span style="font-size: 11pt">Northern Ireland</span><span style="font-size: 11pt"> in accordance with and furtherance of the mission, goal and founding principles of the international Special Olympics movement.</span> 

基本上我想做的是

代码语言:javascript
复制
String.Replace("<span style="font-size: 11pt">","")

但当然,这只会在下一次使用字体大小为8、9或10的时候捕捉到上面的情况,所以filter方法必须像这样智能。

有什么想法吗?

所以现在我得到了类似testSpan = Regex.Replace(testSpan,@"\s]+))?)+\s*|\s*)/?>",String.Empty);

但是它去掉了所有的html,基本上我只是想去掉标签。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-05-27 23:52:15

如果你想学习StackOverflow的例子,你可以创建一个允许的HTML标签的白名单,然后去掉其余的。

以下是Jeff Atwood用来清理和平衡StackOverflow用户生成内容中的HTML标记的代码片段。

允许标记的http://refactormycode.com/codes/333-sanitize-html

  • Balance http://refactormycode.com/codes/360-balance-html-tags

  • 清理

更新

看起来Refactormycode已经死了。以下是我在此之前捕获的一些代码:

代码语言:javascript
复制
/// <summary>
/// Provides some static extension methods for processing strings with HTML in them.
/// </summary>
public static class HtmlStripper
{
    #region Sanitize

    private static readonly Regex Tags = new Regex("<[^>]*(>|$)",
        RegexOptions.Singleline | RegexOptions.ExplicitCapture |
        RegexOptions.Compiled);

    private static readonly Regex Whitelist =
        new Regex(
            @"
^</?(b(lockquote)?|code|d(d|t|l|el)|em|h(1|2|3)|i|kbd|li|ol|p(re)?|s(ub|up|trong|trike)?|ul)>$|
^<(b|h)r\s?/?>$",
            RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled |
            RegexOptions.IgnorePatternWhitespace);

    private static readonly Regex WhitelistA =
        new Regex(
            @"
^<a\s
href=""(\#\d+|(https?|ftp)://[-a-z0-9+&@#/%?=~_|!:,.;\(\)]+)""
(\stitle=""[^""<>]+"")?(\starget=""[^""<>]+"")?\s?>$|
^</a>$",
            RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled |
            RegexOptions.IgnorePatternWhitespace);

    private static readonly Regex WhitelistImg =
        new Regex(
            @"
^<img\s
src=""https?://[-a-z0-9+&@#/%?=~_|!:,.;\(\)]+""
(\swidth=""\d{1,3}"")?
(\sheight=""\d{1,3}"")?
(\salt=""[^""<>]*"")?
(\stitle=""[^""<>]*"")?
\s?/?>$",
            RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled |
            RegexOptions.IgnorePatternWhitespace);


    /// <summary>
    /// sanitize any potentially dangerous tags from the provided raw HTML input using 
    /// a whitelist based approach, leaving the "safe" HTML tags
    /// CODESNIPPET:4100A61A-1711-4366-B0B0-144D1179A937
    /// </summary>
    /// <remarks>
    /// Based on Jeff Atwood's code, found at http://refactormycode.com/codes/333-sanitize-html
    /// Since Jeff Atwood is StackOverflow's administrator, this is most likely the code used by
    /// that site. See http://meta.stackoverflow.com/questions/1777/what-html-tags-are-allowed
    /// for a list of allowed tags.
    /// </remarks>
    public static string SanitizeHtml(string html)
    {
        if (String.IsNullOrEmpty(html)) return html;

        // match every HTML tag in the input
        MatchCollection tags = Tags.Matches(html);
        for (int i = tags.Count - 1; i > -1; i--)
        {
            Match tag = tags[i];
            string tagname = tag.Value.ToLowerInvariant();

            if (!(Whitelist.IsMatch(tagname) || WhitelistA.IsMatch(tagname) || WhitelistImg.IsMatch(tagname)))
            {
                html = html.Remove(tag.Index, tag.Length);
            }
        }

        return html;
    }

    #endregion

    #region Balance tags

    private static readonly Regex Namedtags = new Regex
        (@"</?(?<tagname>\w+)[^>]*(\s|$|>)",
            RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.Compiled);

    /// <summary>
    /// attempt to balance HTML tags in the html string
    /// by removing any unmatched opening or closing tags
    /// IMPORTANT: we *assume* HTML has *already* been 
    /// sanitized and is safe/sane before balancing!
    /// 
    /// CODESNIPPET: A8591DBA-D1D3-11DE-947C-BA5556D89593
    /// </summary>
    /// <remarks>
    /// From Jeff Atwood's post at 
    /// http://refactormycode.com/codes/360-balance-html-tags
    /// </remarks>
    public static string BalanceTags(string html)
    {
        if (String.IsNullOrEmpty(html)) return html;

        // convert everything to lower case; this makes
        // our case insensitive comparisons easier
        MatchCollection tags = Namedtags.Matches(html.ToLowerInvariant());

        // no HTML tags present? nothing to do; exit now
        int tagcount = tags.Count;
        if (tagcount == 0) return html;

        const string ignoredtags = "<p><img><br><li><hr>";
        var tagpaired = new bool[tagcount];
        var tagremove = new bool[tagcount];

        // loop through matched tags in forward order
        for (int ctag = 0; ctag < tagcount; ctag++)
        {
            string tagname = tags[ctag].Groups["tagname"].Value;

            // skip any already paired tags
            // and skip tags in our ignore list; assume they're self-closed
            if (tagpaired[ctag] || ignoredtags.Contains("<" + tagname + ">")) continue;

            string tag = tags[ctag].Value;
            int match = -1;

            if (tag.StartsWith("</"))
            {
                // this is a closing tag
                // search backwards (previous tags), look for opening tags
                for (int ptag = ctag - 1; ptag >= 0; ptag--)
                {
                    string prevtag = tags[ptag].Value;
                    if (!tagpaired[ptag] && prevtag.Equals("<" + tagname, StringComparison.InvariantCulture))
                    {
                        // minor optimization; we do a simple possibly incorrect match above
                        // the start tag must be <tag> or <tag{space} to match
                        if (prevtag.StartsWith("<" + tagname + ">") || prevtag.StartsWith("<" + tagname + " "))
                        {
                            match = ptag;
                            break;
                        }
                    }
                }
            }
            else
            {
                // this is an opening tag
                // search forwards (next tags), look for closing tags
                for (int ntag = ctag + 1; ntag < tagcount; ntag++)
                {
                    if (!tagpaired[ntag] &&
                        tags[ntag].Value.Equals("</" + tagname + ">", StringComparison.InvariantCulture))
                    {
                        match = ntag;
                        break;
                    }
                }
            }

            // we tried, regardless, if we got this far
            tagpaired[ctag] = true;
            if (match == -1) tagremove[ctag] = true; // mark for removal
            else tagpaired[match] = true; // mark paired
        }

        // loop through tags again, this time in reverse order
        // so we can safely delete all orphaned tags from the string
        for (int ctag = tagcount - 1; ctag >= 0; ctag--)
        {
            if (tagremove[ctag])
            {
                html = html.Remove(tags[ctag].Index, tags[ctag].Length);
            }
        }

        return html;
    }

    #endregion
}
票数 0
EN

Stack Overflow用户

发布于 2011-05-27 23:47:45

对于这类事情,你真的应该使用proper HTML parser

票数 2
EN

Stack Overflow用户

发布于 2011-05-27 23:48:11

下面是我用来从VB.NET中的字符串中剥离超文本标记语言的函数:

代码语言:javascript
复制
Public Shared Function StripHTML(ByVal htmlString As String) As String
     Dim pattern As String = "<(.|\n)*?>"
     Return Regex.Replace(htmlString, pattern, String.Empty)
End Function

希望能有所帮助

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/6154645

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档