本文提供一種方法,通過將字符串編碼成Unicode格式,保證數據在展示和傳輸過程中萬無一失。無論客戶端瀏覽器如何改變編碼,頁面上的編碼都不會亂碼。
對于HTML/XML,采用 &# + 十位Unicode碼 + ; 的形式格式化字符。
對于JS,采用 /u + 4位Unicode碼 來格式化字符串.
示例采用C#編寫,使用了 中文、俄文、韓文、日文 來展示。對于PHP,文章末尾將會提到。
首先,有一個String的擴展類。
復制代碼 代碼如下:
using System.Text.RegularExpressions;
namespace XXOO
{
/// <summary>
/// 擴展方法,提供Html編碼 和 腳本編碼
/// </summary>
public static class StringExtension
{
private static string GetHtmlEncodedStr(Match m)
{
string x = m.ToString();
return string.Format("&#{0};", (int)x[0]);
}
/// <summary>
/// 將字符串轉換為HTML編碼格式
/// </summary>
/// <param name="text">字符串</param>
/// <returns>輸出形如:中文豐厚警</returns>
public static string HtmlEncode( this string text )
{
return Regex.Replace(text
, "([^//000-//127]|&|///"|//<|//>|')"
, new MatchEvaluator(GetHtmlEncodedStr)
, RegexOptions.ECMAScript | RegexOptions.Compiled
);
}
private static string GetScriptEncodedStr(Match m)
{
string x = m.ToString();
return "http://u" + string.Format("{0:X}", (int)x[0]).PadLeft( 4, '0');
}
/// <summary>
/// 將字符串編碼成Unicode格式 如:/uXXXX
/// </summary>
/// <param name="text">字符串</param>
/// <returns>輸出形如:/u4E2D/u6587/u4E30/u539A/u8B66/u65B9</returns>
public static string ScriptEncode( this string text )
{
return Regex.Replace(text
, "([^//000-//127]|&|///"|'|//<|//>|//n|//r|//t)"
, new MatchEvaluator(GetScriptEncodedStr)
, RegexOptions.ECMAScript | RegexOptions.Compiled
);
}
}
}
它提供了2個方法,給測試頁面使用。
測試頁面(ASP.Net)
復制代碼 代碼如下:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<pre runat="Server" id="pre"></pre>
<asp:PlaceHolder runat="Server" ID="placeHolder"></asp:PlaceHolder>
</form>
</body>
</html>
測試頁面代碼:
復制代碼 代碼如下: