基于行数预测的长文章分页2010-09-16 博客园 依诺说句老实话,我是个不大习惯写博的主,而且本次写博目的是想过来发个小广告,哈哈,都是园子里的兄弟不要拿砖头扔我园子里的兄弟时间都是很宝贵的.为了大家消消火,少让大家过来扔砖头.所以就把最近项目里碰到的一个长文章自动分页的问题跟大家分享下.说起长文章分页也是属于老生常谈了,网上搜下可以找到一箩筐。目前网上流传的代码大多是基于对文章中字符的多少来进行,这种方法对于图片等这些标记就束手无策了。由于目前文章上传大多采用HTML编辑器,使得里面参杂的HTML代码严重影响到场文章分页的效果。我现在想说的是一种基于文章行数预测为思路的一种分页方式.操作过程也很简单.大家都是写程序的,费话少说,看代码 1 //======================================================
2
3 // 50M 双线空间 + 10M数据库 + 50M邮箱 18元/年
4 // 100M 双线空间 + 50M数据库 + 100M邮箱 28元/年
5 // 200M 双线空间 + 50M数据库 + 100M邮箱 38元/年
6 // 特价主机,有需要的M我 QQ:70975363
7
8 //======================================================
9
10 private static List<string> HtmlLineTest(ref string content, int pageid, string url)
11 {
12 //文章分段数组
13 List<string> segs = new List<string>();
14 int segmax = 30; // 计划每一面的行数
15 int linewords = 50;
16 int segmin = 0;
17
18 string s;
19
20 //int pageheight = 25;
21 int line = 0;
22 对含有HTML代码的文章进行整理#region 对含有HTML代码的文章进行整理
23 content = Regex.Replace(content, "<p[^<>]*>", "", RegexOptions.IgnoreCase);
24 content = Regex.Replace(content, "<div[^<>]*>", "", RegexOptions.IgnoreCase);
25 content = Regex.Replace(content, "</p>", "<br />", RegexOptions.IgnoreCase);
26 content = Regex.Replace(content, "</div>", "", RegexOptions.IgnoreCase);
27 #endregion
28 MatchCollection mcc = Regex.Matches(content, "<br */*>|<img[^<>]+>", RegexOptions.IgnoreCase);
29 int idx = 0;
30 StringBuilder __article = new StringBuilder();
31 foreach (Match m in mcc)
32 {
33 if (m.Value.StartsWith("<br", StringComparison.OrdinalIgnoreCase))
34 {
35 s = content.Substring(idx, m.Index - idx);
36 if (!s.StartsWith(" "))
37 __article.Append(" ");
38 __article.Append(s);
39 idx = m.Index + m.Value.Length;
40 int lth = s.Length / linewords;
41 if (s.Length % linewords < linewords/2)
42 lth++;
43 line += lth == 0 ? 1 : lth;
44 segmin += lth == 0 ? 1 : lth;
45 __article.Append("<br />");
46 if (segmax <= segmin)
47 {
48 segs.Add(__article.ToString());
49 _string.Remove(0, __article.Length);
50 segmin = 0;
51 }
52 }
53 else if (m.Value.StartsWith("<img", StringComparison.OrdinalIgnoreCase))
54 {
55 int pos = m.Value.IndexOf("height");
56 if (pos > -1)
57 {
58
59 string ms = m.Value.Substring(pos + 6);
60 pos = int.Parse(Regex.Match(ms, "\d+").Value);
61 line += pos / 25;
62 segmin += pos / 25;
63 }
64 else
65 {
66 // 图片没有发现表示高度的属性
67 line += 400 / 25;
68 segmin += 400 / 25;
69 }
70 idx = m.Index + m.Value.Length;
71 __article.Append(m.Value);
72 __article.Append("<br />");
73 if (segmax <= segmin)
74 {
75 segs.Add(_string.ToString());
76 __article.Remove(0, _string.Length);
77 segmin = 0;
78 }
79 }
80 }
81 if(__article.Length>0)
82 segs.Add(_string.ToString());
83 if (mcc.Count == 0)
84 segs.Add(content);
85 return segs;
86 }