不破坏html c#的子字符串

本文关键字:字符串 html | 更新日期: 2023-09-27 17:57:31

大家好,我正在尝试获取一个在wysiwyg编辑器中输入的描述,并获取它的子字符串。

This is some <span style="font-weight:bold;">text</span>

我想在不破坏html的情况下限制一些描述,如果我只是添加子字符串。。。

它破坏了html标签。。

我试过:

string HtmlSubstring(string html, int maxlength)
    {
        string htmltag = "</?''w+((''s+''w+(''s*=''s*(?:'".*?'"|'.*?'|[^''">''s]+))?)+''s*|''s*)/?>";
        string emptytags = "<(''w+)((''s+''w+(''s*=''s*(?:'".*?'"|'.*?'|[^''">''s]+))?)+''s*|''s*)/?></''1>";
        var expression = new Regex(string.Format("({0})|(.?)", htmltag));
        MatchCollection matches = expression.Matches(html);
        int i = 0;
        StringBuilder content = new StringBuilder();
        foreach (Match match in matches)
        {
            if (match.Value.Length == 1 && i < maxlength)
            {
                content.Append(match.Value);
                i++;
            }
            else if (match.Value.Length > 1)
            {
                content.Append(match.Value);
            }
        }
        return Regex.Replace(content.ToString(), emptytags, string.Empty);
    }

但这并不能让我达到目的!

不破坏html c#的子字符串

使用HTML敏捷包加载HTML,然后获取InnerText。

var document = new HtmlDocument();
document.LoadHtml("...");
document.DocumentNode.InnerText;

另请参见C#:HtmlAgilityPack提取内部文本