去除html中的javascript代码和其他标签

昨天憋了一下午也没搞定,今天早上终于解决了多行匹配的问题。

protected static string parseHtml(string html)
{
string clearScriptPattern = @"<\s*script[^>]*>(.|\n)*?<\/\s*script\s*>“;//前面去掉空格,中间(.|\n)*?为非贪婪匹配
string clearStylePattern = @”<\s*style\s*>(.|\n)*?“;
string clearHtmlPattern = @”<[^>]*>”;
string clearSpacePattern = @” |&nbsp|\s”;
RegexOptions options = RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled;

string parseResult = Regex.Replace(html, clearScriptPattern, “”, options);
parseResult = Regex.Replace(parseResult, clearStylePattern, “”, options);
parseResult = Regex.Replace(parseResult, clearHtmlPattern, “”, options);
parseResult = Regex.Replace(parseResult, clearSpacePattern, ” “, options);
return parseResult;
}

推荐一个代码重构的工具Refactor!™ Pro,如果想自己的代码写得漂亮一点,用它没错。

[ 分类: 学习 ] 由 Pan 发表于 June 18, 2007 8:54 pm  固定链接 

去除html中的javascript代码和其他标签》 这篇文章一共有1 条评论   我也想说两句

  1. me

    November 22, 2007 9:52 am

    另外一个例子
    #region 过滤掉 html代码
    public static string StripHTML(string strHtml)
    {
    string [] aryReg ={
    @”]*?>.*?”,

    @”",
    @”([\r\n])[\s]+”,
    @”&(quot|#34);”,
    @”&(amp|#38);”,
    @”&(lt|#60);”,
    @”&(gt|#62);”,
    @”&(nbsp|#160);”,
    @”&(iexcl|#161);”,
    @”&(cent|#162);”,
    @”&(pound|#163);”,
    @”&(copy|#169);”,
    @”&#(\d+);”,
    @”–>”,
    @”",
    ” “,
    “\xa1″,//chr(161),
    “\xa2″,//chr(162),
    “\xa3″,//chr(163),
    “\xa9″,//chr(169),
    “”,
    “\r\n”,
    “”
    };

    string newReg =aryReg[0];
    string strOutput=strHtml;
    for(int i = 0;i”,”");
    strOutput.Replace(”\r\n”,”");
    return strOutput;
    }
    #endregion

RSS feed for comments on this post. TrackBack URI

相关文章:

发表评论