漢字都轉化爲了html實體(十進制表示的Unicode編碼),這樣做的好處就是不管網頁的編碼是什麼,都可以正常的顯示漢字,而不會出現亂碼,當然也適用於其他字符集。
在php中我們可以用mbstring的mb_convert_encoding函數實現這個正向及反向的轉化。
如:
mb_convert_encoding ("你好", "gb2312", "HTML-ENTITIES"); //輸出:你好
如果需要對整個頁面轉化,則只需要在php文件的頭部加上這三行代碼:
mb_internal_encoding("gb2312"); // 這裏的gb2312是你網站原來的編碼
mb_http_output("HTML-ENTITIES");
ob_start('mb_output_handler');
Asp版 可以用下面這個函數來實現這個轉化:
Function htmlentities(str)
For i = 1 to Len(str)
char = mid(str, i, 1)
If AscW(char) > 0 then
htmlentities = htmlentities & "&#" & Ascw(char) & ";"
Else
htmlentities = htmlentities & "&#" & (65536 + ascW(char)) & ";"
End if
Next
End Function
JS 版
function htmlentities(str)
{
var r = "";
for( i=0; i<str.length; i++ )
{
temp = str.charCodeAt(i);
r += "&#"+temp+";";
}
// 也可以用一句正則表達式解決
// r = str.replace(/[\d\D]/g, function($0) { return "&#" + $0.charCodeAt(0) + ";"; });
return r;
}
asp.net (c#) 版
private string GetHtmlEntities(string str)
{
string r = string.Empty;
for (int i = 0; i < str.Length; i++)
{
r += "&#"+Char.ConvertToUtf32(str,i)+";";
}
return r;
}