替換、恢複Html中的特殊字元

來源:互聯網
上載者:User

標籤:

public static string HtmlEncode(string theString)
{
theString = theString.Replace(">", ">");
theString = theString.Replace("<", "&lt;");
theString = theString.Replace(" ", " &nbsp;");
theString = theString.Replace(" ", " &nbsp;");
theString = theString.Replace("\"", "&quot;");
theString = theString.Replace("\‘", "&#39;");
theString = theString.Replace("\n", "<br/> ");
return theString;
}
第一段是轉換textarea裡面的特殊字元的,用處是:比如在做網頁的時候,提供了一個textarea框給使用者,讓使用者輸入一個自我簡介什麼的,然後儲存到資料庫裡,在儲存到庫裡以前要做一下這樣的轉換,為了安全考慮,還有就是特殊字元這樣轉換後才能保留,不然在textarea裡敲空格和斷行符號,在儲存的時候,這些是沒有了的,輸出到網頁上會發現,什麼格式都沒有了。
public static string HtmlDiscode(string theString)
{
theString = theString.Replace("&gt;", ">");
theString = theString.Replace("&lt;", "<");
theString = theString.Replace("&nbsp;", " ");
theString = theString.Replace(" &nbsp;", " ");
theString = theString.Replace("&quot;", "\"");
theString = theString.Replace("&#39;", "\‘");
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中的特殊字元

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.