• 截取HTML C#代码

    香水坏坏 发表于2007-7-7 [ASP.NET]

    。。。。。。。头晕 肯定还没考虑完善 闷。。。

     

    C#代码
    1. protected string TrimHtml(string input, int length)   
    2. {   
    3. string inputHTML = input.Trim();   
    4. StringBuilder outHTML = new StringBuilder();   
    5.   
    6. int maxLength = length;   
    7. if (maxLength < inputHTML.Length)   
    8. {   
    9. inputHTML = inputHTML.Substring(0, 505);   
    10.   
    11. string firstMatch = "";   
    12. string lastMatch = "";   
    13. bool isRegexMatch = false;   
    14.   
    15. string patternMatchHTML = @"(<([a-z0-9]*)([^>]*)>(.*)<\s*/\s*\2>)|(<([a-z0-9]*)([^>]*)/\s*>)”;  
    16. Regex regex = new Regex(patternMatchHTML, RegexOptions.IgnoreCase);  
    17. Match m = regex.Match(inputHTML);  
    18. while(m.Success)  
    19. {  
    20. isRegexMatch = true;  
    21. if (firstMatch==”")   
    22. firstMatch = m.Value;   
    23. lastMatch = m.Value;   
    24. outHTML.Append(m.Value);   
    25.   
    26. m = m.NextMatch();   
    27.   
    28. }   
    29. if (isRegexMatch)   
    30. {   
    31. string beforeString = “”;   
    32. if (firstMatch != “”)   
    33. {   
    34. beforeString = inputHTML.Substring(0, inputHTML.IndexOf(firstMatch));   
    35. }   
    36. bool hasMeetingTag = false;   
    37. for (int i = beforeString.Length - 1; i >= 0; i–)   
    38. {   
    39. if (beforeString[i] == ‘>’)   
    40. {   
    41. hasMeetingTag = true;   
    42. }   
    43. else if (beforeString[i] == ‘<')  
    44. {  
    45. hasMeetingTag = false;  
    46. }  
    47. else  
    48. {  
    49. if (!hasMeetingTag)  
    50. outHTML.Insert(0, beforeString[i]);  
    51. }  
    52. }  
    53.  
    54. string lastString = "";  
    55. if (lastMatch != "")  
    56. {  
    57. lastString = inputHTML.Substring(inputHTML.LastIndexOf(lastMatch) + lastMatch.Length);  
    58. }  
    59. hasMeetingTag = false;  
    60. for (int i = 0; i < lastString.Length; i++)  
    61. {  
    62. if (lastString[i] == '<')  
    63. {  
    64. hasMeetingTag = true;  
    65. }  
    66. else if (lastString[i] == '>‘)   
    67. {   
    68. hasMeetingTag = false;   
    69. }   
    70. else  
    71. {   
    72. if (!hasMeetingTag)   
    73. outHTML.Append(lastString[i]);   
    74. }   
    75. }   
    76. }   
    77. else  
    78. {   
    79. outHTML.Append(inputHTML);   
    80. }   
    81. }   
    82. else  
    83. {   
    84. outHTML.Append(inputHTML);   
    85. }   
    86. return outHTML.ToString().Trim();   
    87. }   
    88.   

     

    Hits: 731  Feedback: 0  标签:HTML  Trackback  Permalink: http://www.aspstat.com/41