標籤:
public static string HtmlEncode(string theString)
{
theString = theString.Replace(">", ">");
theString = theString.Replace("<", "<");
theString = theString.Replace(" ", " ");
theString = theString.Replace(" ", " ");
theString = theString.Replace("\"", """);
theString = theString.Replace("\‘", "'");
theString = theString.Replace("\n", "<br/> ");
return theString;
}
第一段是轉換textarea裡面的特殊字元的,用處是:比如在做網頁的時候,提供了一個textarea框給使用者,讓使用者輸入一個自我簡介什麼的,然後儲存到資料庫裡,在儲存到庫裡以前要做一下這樣的轉換,為了安全考慮,還有就是特殊字元這樣轉換後才能保留,不然在textarea裡敲空格和斷行符號,在儲存的時候,這些是沒有了的,輸出到網頁上會發現,什麼格式都沒有了。
public static string HtmlDiscode(string theString)
{
theString = theString.Replace(">", ">");
theString = theString.Replace("<", "<");
theString = theString.Replace(" ", " ");
theString = theString.Replace(" ", " ");
theString = theString.Replace(""", "\"");
theString = theString.Replace("'", "\‘");
theString = theString.Replace("<br/> ", "\n");
return theString;
}
這段段代碼正好與第一段代碼相反,比如,使用者登入後,要修改簡歷,你要把你儲存的簡歷放入到textarea裡,就必須再做一次反向轉換,不然會顯示一些不是使用者輸入的字元。
public static string DealHtml(string str)
{
str = Regex.Replace(str, @"\<(img)[^>]*>|<\/(img)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<(table|tbody|tr|td|th|)[^>]*>|<\/(table|tbody|tr|td|th|)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<(div|blockquote|fieldset|legend)[^>]*>|<\/(div|blockquote|fieldset|legend)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<(font|i|u|h[1-9]|s)[^>]*>|<\/(font|i|u|h[1-9]|s)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<(style|strong)[^>]*>|<\/(style|strong)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<a[^>]*>|<\/a>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<(meta|iframe|frame|span|tbody|layer)[^>]*>|<\/(iframe|frame|meta|span|tbody|layer)>", "", RegexOptions.IgnoreCase);
str = Regex.Replace(str, @"\<a[^>]*", "", RegexOptions.IgnoreCase);
return st
這段代碼是用Regex過濾html標記的,它提到的html標記都會被過濾掉
比如在發表文章的時候,用的是html線上編輯器,這樣會讓文章內容包含html代碼,如果這時候,你想到網站首頁上顯示一部分文章內容,這個時間如果你直接截取文章內容,可能會把包含的html代碼截斷開,這樣在首頁上顯示的html代碼不全,會導致出現一些破碎的html代碼,我們一般的做法就是把html代碼過濾掉,只剩文字,這樣顯示出來再用css格式化,在首頁上,就好看多了,這個函數,就是把str過濾成純淨的文字,不包含html的
替換、恢複Html中的特殊字元