本文提供一種方法,通過將字符串編碼成Unicode格式,保證數(shù)據(jù)在展示和傳輸過程中萬無一失。無論客戶端瀏覽器如何改變編碼,頁面上的編碼都不會亂碼。
對于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>
/// 將字符串轉(zhuǎn)換為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 "\\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>
測試頁面代碼:
復制代碼 代碼如下:
using XXOO;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
var str = @"中文豐厚警方過后發(fā)達看見發(fā)的話該快發(fā)動機后購房貸款好
Китайское посольство в Ираке и Багдаде отделение
이라크에서 중국 대사관과 알의 바그다드 지사 - 만수르 호텔
イラクでの大使館やアルのバグダッド支局-マンスールホテル
1234567890!@#$%^*()>""'\|}{][:;
";
pre.InnerHtml = str.HtmlEncode();
HtmlGenericControl control = new HtmlGenericControl("script");
control.Attributes["language"] = "javascript";
control.Attributes["type"] = "text/javascript";
control.InnerHtml = string.Format("alert(\"{0}\");", str.ScriptEncode());
placeHolder.Controls.Add(control);
}
}
}
運行后得到的HTML:
復制代碼 代碼如下:
!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>title>
/title>/head>
body>
form name="form1" method="post" action="WebForm1.aspx" id="form1">
pre id="pre">#20013;#25991;#20016;#21402;#35686;#26041;#36807;#21518;#21457;#36798;#30475;#35265;#21457;#30340;#35805;#35813;#24555;#21457;#21160;#26426;#21518;#36141;#25151;#36151;#27454;#22909;
#1050;#1080;#1090;#1072;#1081;#1089;#1082;#1086;#1077; #1087;#1086;#1089;#1086;#1083;#1100;#1089;#1090;#1074;#1086; #1074; #1048;#1088;#1072;#1082;#1077; #1080; #1041;#1072;#1075;#1076;#1072;#1076;#1077; #1086;#1090;#1076;#1077;#1083;#1077;#1085;#1080;#1077;
#51060;#46972;#53356;#50640;#49436; #51473;#44397; #45824;#49324;#44288;#44284; #50508;#51032; #48148;#44536;#45796;#46300; #51648;#49324; - #47564;#49688;#47476; #54840;#53588;
#12452;#12521;#12463;#12391;#12398;#22823;#20351;#39208;#12420;#12450;#12523;#12398;#12496;#12464;#12480;#12483;#12489;#25903;#23616;-#12510;#12531;#12473;#12540;#12523;#12507;#12486;#12523;
1234567890!@#$%#94;#38;*()#60;#62;#34;#39;#92;#124;#125;#123;#93;#91;:;
/pre>
script language="javascript" type="text/javascript">!--
alert("\u4E2D\u6587\u4E30\u539A\u8B66\u65B9\u8FC7\u540E\u53D1\u8FBE\u770B\u89C1\u53D1\u7684\u8BDD\u8BE5\u5FEB\u53D1\u52A8\u673A\u540E\u8D2D\u623F\u8D37\u6B3E\u597D\u000D\u000A\u041A\u0438\u0442\u0430\u0439\u0441\u043A\u043E\u0435 \u043F\u043E\u0441\u043E\u043B\u044C\u0441\u0442\u0432\u043E \u0432 \u0418\u0440\u0430\u043A\u0435 \u0438 \u0411\u0430\u0433\u0434\u0430\u0434\u0435 \u043E\u0442\u0434\u0435\u043B\u0435\u043D\u0438\u0435 \u000D\u000A\uC774\uB77C\uD06C\uC5D0\uC11C \uC911\uAD6D \uB300\uC0AC\uAD00\uACFC \uC54C\uC758 \uBC14\uADF8\uB2E4\uB4DC \uC9C0\uC0AC - \uB9CC\uC218\uB974 \uD638\uD154\u000D\u000A\u30A4\u30E9\u30AF\u3067\u306E\u5927\u4F7F\u9928\u3084\u30A2\u30EB\u306E\u30D0\u30B0\u30C0\u30C3\u30C9\u652F\u5C40-\u30DE\u30F3\u30B9\u30FC\u30EB\u30DB\u30C6\u30EB\u000D\u000A1234567890!@#$%\u005E\u0026*()\u003C\u003E\u0022\u0027\u005C\u007C\u007D\u007B\u005D\u005B:;\u000D\u000A");
// -->/script>
/form>
/body>
/html>
!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>title>
/title>/head>
body>
form name="form1" method="post" action="WebForm1.aspx" id="form1">
pre id="pre">#20013;#25991;#20016;#21402;#35686;#26041;#36807;#21518;#21457;#36798;#30475;#35265;#21457;#30340;#35805;#35813;#24555;#21457;#21160;#26426;#21518;#36141;#25151;#36151;#27454;#22909;
#1050;#1080;#1090;#1072;#1081;#1089;#1082;#1086;#1077; #1087;#1086;#1089;#1086;#1083;#1100;#1089;#1090;#1074;#1086; #1074; #1048;#1088;#1072;#1082;#1077; #1080; #1041;#1072;#1075;#1076;#1072;#1076;#1077; #1086;#1090;#1076;#1077;#1083;#1077;#1085;#1080;#1077;
#51060;#46972;#53356;#50640;#49436; #51473;#44397; #45824;#49324;#44288;#44284; #50508;#51032; #48148;#44536;#45796;#46300; #51648;#49324; - #47564;#49688;#47476; #54840;#53588;
#12452;#12521;#12463;#12391;#12398;#22823;#20351;#39208;#12420;#12450;#12523;#12398;#12496;#12464;#12480;#12483;#12489;#25903;#23616;-#12510;#12531;#12473;#12540;#12523;#12507;#12486;#12523;
1234567890!@#$%#94;#38;*()#60;#62;#34;#39;#92;#124;#125;#123;#93;#91;:;
/pre>
script language="javascript" type="text/javascript">!--
alert("\u4E2D\u6587\u4E30\u539A\u8B66\u65B9\u8FC7\u540E\u53D1\u8FBE\u770B\u89C1\u53D1\u7684\u8BDD\u8BE5\u5FEB\u53D1\u52A8\u673A\u540E\u8D2D\u623F\u8D37\u6B3E\u597D\u000D\u000A\u041A\u0438\u0442\u0430\u0439\u0441\u043A\u043E\u0435 \u043F\u043E\u0441\u043E\u043B\u044C\u0441\u0442\u0432\u043E \u0432 \u0418\u0440\u0430\u043A\u0435 \u0438 \u0411\u0430\u0433\u0434\u0430\u0434\u0435 \u043E\u0442\u0434\u0435\u043B\u0435\u043D\u0438\u0435 \u000D\u000A\uC774\uB77C\uD06C\uC5D0\uC11C \uC911\uAD6D \uB300\uC0AC\uAD00\uACFC \uC54C\uC758 \uBC14\uADF8\uB2E4\uB4DC \uC9C0\uC0AC - \uB9CC\uC218\uB974 \uD638\uD154\u000D\u000A\u30A4\u30E9\u30AF\u3067\u306E\u5927\u4F7F\u9928\u3084\u30A2\u30EB\u306E\u30D0\u30B0\u30C0\u30C3\u30C9\u652F\u5C40-\u30DE\u30F3\u30B9\u30FC\u30EB\u30DB\u30C6\u30EB\u000D\u000A1234567890!@#$%\u005E\u0026*()\u003C\u003E\u0022\u0027\u005C\u007C\u007D\u007B\u005D\u005B:;\u000D\u000A");
// -->/script>
/form>
/body>
/html>
這樣,不管瀏覽器采用何種編碼,頁面都不會出現(xiàn)亂碼。
==============================================
PHP
PHP的情況就復雜一點,需要考慮mysql的編碼。這些姑且不論。
下面給出一點示例,將GBK進行HTML編碼。僅作參考:
復制代碼 代碼如下:
function htmlEncode($text)
{
$encoded = "";
for( $index = 0; $index strlen($text); $index++)
{
if( ord($text[$index]) = 127 )
{
switch(ord($text[$index]))
{
case 34:
case 38:
case 39:
case 60:
case 62:
$encoded .= "#" .ord($text[$index]).";";
break;
default:
$encoded .= $text[$index];
}
}
else
{
$char = $text[$index] . $text[$index+1];
$char = mb_convert_encoding( $char, "utf-16", "gbk");
$encoded .= "#" . (ord($char[0])*256 + ord($char[1])) . ";";
$index++;
}
}
return $encoded;
}
function htmlEncode($text)
{
$encoded = "";
for( $index = 0; $index strlen($text); $index++)
{
if( ord($text[$index]) = 127 )
{
switch(ord($text[$index]))
{
case 34:
case 38:
case 39:
case 60:
case 62:
$encoded .= "#" .ord($text[$index]).";";
break;
default:
$encoded .= $text[$index];
}
}
else
{
$char = $text[$index] . $text[$index+1];
$char = mb_convert_encoding( $char, "utf-16", "gbk");
$encoded .= "#" . (ord($char[0])*256 + ord($char[1])) . ";";
$index++;
}
}
return $encoded;
}
然后通過XML返回,這樣就能夠徹底杜絕亂碼。
復制代碼 代碼如下:
echo "?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
echo "result>";
echo "success>". ($success ? 1 : 0) ."/success>";
echo "message>" . htmlEncode($message) . "/message>";
if( $success )
{
echo "nickname>" . htmlEncode($nickname) . "/nickname>";
echo "userId>".$userId."/userId>";
echo "siteId>".$siteId."/siteId>";
echo "isTeacher>". ($isTeacher ? 1 : 0) ."/isTeacher>";
echo "ipAddress>" . htmlEncode($ipAddress) . "/ipAddress>";
}
echo "/result>";
本文來自CSDN博客,轉(zhuǎn)載請標明出處:http://blog.csdn.net/wangjia184/archive/2009/10/26/4728318.aspx