UTF-8转unicode PHP版本+Javascript版本
PHP代码
- function uni($str) {
- $ret = ”;
- for($i=0;$i<mb_strlen($str,‘utf-8′);$i=$i+1) {
- $ret .= "&#" . uniord(mb_substr($str, $i, 1, ‘utf-8′)) . ";";
- }
- return $ret;
- }
- echo uni("海海家园");
- function unichr($u) {
- return mb_convert_encoding(pack("N",$u), mb_internal_encoding(), ‘UCS-4BE’);
- }
- function uniord($u) {
- $c = unpack("N", mb_convert_encoding($u, ‘UCS-4BE’, ‘UTF-8′));
- return $c[1];
- }
JavaScript 版本
JavaScript代码
-
</li>
</ol>
</div>
从朋友那得到的新方法:(2007.8.14)
JavaScript代码
- <script language="javascript" type="text/javascript">
- var oSource = document.getElementById("source");
- var oShow2 = document.getElementById("show2");
- var oTt = document.getElementById("tt");
- function action(pChoice){
- switch(pChoice){
- case "CONVERT_FMT1":
- oShow2.value = ascii(oSource.value);
- break;
- case "CONVERT_FMT2":
- oShow2.value = unicode(oSource.value);
- break;
- case "RECONVERT":
- oShow2.value = reconvert(oSource.value);
- break;
- }
- }
- function ascii(str){
- return str.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\$2;")});
- }
- function unicode(str){
- return str.replace(/[^\u0000-\u00FF]/g,function($0){return escape($0).replace(/(%u)(\w{4})/gi,"\\u$2")});
- }
- function reconvert(str){
- str = str.replace(/(\\u)(\w{4})/gi,function($0){
- return (String.fromCharCode(parseInt((escape($0).replace(/(%5Cu)(\w{4})/g,"$2")),16)));
- });
- str = str.replace(/()(\w{4});/gi,function($0){
- return String.fromCharCode(parseInt(escape($0).replace(/(%26%23x)(\w{4})(%3B)/g,"$2"),16));
- });
- return str;
- }
- </script>