2011-06-17 52 views
7

我將html作爲帶有javascript和css代碼塊的字符串。.Net從html頁面中刪除javascript和css代碼塊

事情是這樣的:

<script type="text/javascript"> 

    alert('hello world'); 

</script> 

<style type="text/css"> 
    A:link {text-decoration: none} 
    A:visited {text-decoration: none} 
    A:active {text-decoration: none} 
    A:hover {text-decoration: underline; color: red;} 
</style> 

但我不需要他們。我怎樣才能刪除與reqular表達式這些塊?

回答

15

快速 'N' 髒的方法是這樣的正則表達式:

var regex = new Regex(
    "(\\<script(.+?)\\</script\\>)|(\\<style(.+?)\\</style\\>)", 
    RegexOptions.Singleline | RegexOptions.IgnoreCase 
); 

string ouput = regex.Replace(input, ""); 

更好*(但可能更慢)的選擇是使用HtmlAgilityPack

HtmlDocument doc = new HtmlDocument(); 
doc.LoadHtml(htmlInput); 

var nodes = doc.DocumentNode.SelectNodes("//script|//style"); 

foreach (var node in nodes) 
    node.ParentNode.RemoveChild(node); 

string htmlOutput = doc.DocumentNode.OuterHtml; 

*)對於關於爲什麼更好的討論,請參見this thread

+3

你知道嗎[託尼小馬](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454)? – GvS 2011-06-17 09:24:15

+1

@GvS:我知道在使用正則表達式處理HTML時可能會出現的問題。因此,對於大多數情況下,我會強烈建議像HtmlAgilityPack這樣的html解析器,但這取決於情況。如果是一次性刪除腳本和樣式塊,並且我知道輸入是有效的html,那麼我的上述正則表達式就足夠了,尤其是因爲'

1

只要找一個開放的<script標記,然後刪除它和關閉/script>標記之間的所有內容。

同樣的風格。 See Google爲字符串操作提示。

+0

不一樣,如果您的代碼文件撰寫(「」)在其 – 2011-06-17 10:58:24

+0

是它足以只是這樣做的安全感的工作? (阻止JavaScript執行)? – Bamboo 2014-05-23 07:23:54

2

使用HTMLAgilityPack獲得更好的結果

或嘗試這個功能

public string RemoveScriptAndStyle(string HTML) 
{ 
    string Pat = "<(script|style)\\b[^>]*?>.*?</\\1>"; 
    return Regex.Replace(HTML, Pat, "", RegexOptions.IgnoreCase | RegexOptions.Singleline); 
} 
1

我做了我的自行車),他可能不會像HtmlAgilityPack是正確的,但它的速度要快得多了約5-6倍於400 kb的頁面。另外,還要小寫符號和刪除數字(標記生成器製造)

private static readonly List<byte[]> SPECIAL_TAGS = new List<byte[]> 
                  { 
                   Encoding.ASCII.GetBytes("script"), 
                   Encoding.ASCII.GetBytes("style"), 
                   Encoding.ASCII.GetBytes("noscript") 
                  }; 

    private static readonly List<byte[]> SPECIAL_TAGS_CLOSE = new List<byte[]> 
                    { 
                     Encoding.ASCII.GetBytes("/script"), 
                     Encoding.ASCII.GetBytes("/style"), 
                     Encoding.ASCII.GetBytes("/noscript")}; 

public static string StripTagsCharArray(string source, bool toLowerCase) 
    { 
     var array = new char[source.Length]; 
     var arrayIndex = 0; 
     var inside = false; 
     var haveSpecialTags = false; 
     var compareIndex = -1; 
     var singleQouteMode = false; 
     var doubleQouteMode = false; 
     var matchMemory = SetDefaultMemory(SPECIAL_TAGS); 
     for (int i = 0; i < source.Length; i++) 
     { 
      var let = source[i]; 
      if (inside && !singleQouteMode && !doubleQouteMode) 
      { 
       compareIndex++; 
       if (haveSpecialTags) 
       { 
        var endTag = CheckSpecialTags(let, compareIndex, SPECIAL_TAGS_CLOSE, ref matchMemory); 
        if (endTag) haveSpecialTags = false; 
       } 
       if (!haveSpecialTags) 
       { 
        haveSpecialTags = CheckSpecialTags(let, compareIndex, SPECIAL_TAGS, ref matchMemory); 
       } 
      } 
      if (haveSpecialTags && let == '"') 
      { 
       doubleQouteMode = !doubleQouteMode; 
      } 
      if (haveSpecialTags && let == '\'') 
      { 
       singleQouteMode = !singleQouteMode; 
      } 
      if (let == '<') 
      { 
       matchMemory = SetDefaultMemory(SPECIAL_TAGS); 
       compareIndex = -1; 
       inside = true; 
       continue; 
      } 
      if (let == '>') 
      { 
       inside = false; 
       continue; 
      } 
      if (inside) continue; 
      if (char.IsDigit(let)) continue; 
      if (haveSpecialTags) continue; 
      array[arrayIndex] = toLowerCase ? Char.ToLowerInvariant(let) : let; 
      arrayIndex++; 
     } 
     return new string(array, 0, arrayIndex); 
    } 

    private static bool[] SetDefaultMemory(List<byte[]> specialTags) 
    { 
     var memory = new bool[specialTags.Count]; 
     for (int i = 0; i < memory.Length; i++) 
     { 
      memory[i] = true; 
     } 
     return memory; 
    }