码迷,mamicode.com
首页 > Web开发 > 详细

网站博客截取简介

时间:2020-01-10 16:02:05      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:dex   count   regex   def   length   regexp   match   tst   The   

 

      public static string HtmlCutString(string str, int length, string character = "")
        {
            str = System.Web.HttpUtility.HtmlDecode(str.Replace("\r\n", ""));
            int len = 0, tagIndex = 0, strlength = str.Length;
            Regex objRegExp = new Regex("(<.+?>)", RegexOptions.IgnoreCase);
            MatchCollection matches = objRegExp.Matches(str);
            for (int i = 0; i < strlength; i++)
            {
                if (matches.Count > tagIndex && i == matches[tagIndex].Index)
                {
                    i += matches[tagIndex].Result("$1").Length - 1;
                    tagIndex++;
                }
                else
                {
                    if (System.Text.Encoding.Default.GetBytes(str.Substring(i, 1)).Length > 1)
                        len += 2;
                    else
                        len += 1;
                }
                if (len >= length)
                {
                    string other = "";
                    while (matches.Count > tagIndex)
                    {
                        other += matches[tagIndex].Value;
                        tagIndex++;
                    }
                    int otherlength = other.Length;
                    objRegExp = new Regex(@"<\s*\b(.+?)\b[^>]*?><\s*/\s*\b\1\b\s*>|<\s*\b(.+?)\b.*?/\s*>", RegexOptions.IgnoreCase);
                    while (objRegExp.Matches(other).Count > 0)
                    {
                        other = objRegExp.Replace(other, "");
                    }
                    other = new Regex(@"<\s*[^/]+?>", RegexOptions.IgnoreCase).Replace(other, "");
                    if (i + otherlength + 1 < strlength)
                        str = str.Substring(0, i + 1 - character.Length) + character + other;
                    else
                        str = str.Substring(0, i + 1) + other;
                    break;
                }
            }
            return str;
        }

 

网站博客截取简介

标签:dex   count   regex   def   length   regexp   match   tst   The   

原文地址:https://www.cnblogs.com/wangyinlon/p/12176222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!