可以将二进制转成十六进制,然后再传给js进行处理,转成二进制,示例代码如下:
<?php
$str = '回';
$bin = pack("C3", ord($str{0}), ord($str{1}), ord($str{2}));
$hex = bin2hex($bin);
echo $hex;
?>
<script type="text/javascript">
function hexStringToArrayBuffer(hexString) {
// remove the leading 0x
hexString = hexString.replace(/^0x/, '');
// ensure even number of characters
if (hexString.length % 2 != 0) {
console.log('WARNING: expecting an even number of characters in the hexString');
}
// check for some non-hex characters
var bad = hexString.match(/[G-Z\s]/i);
if (bad) {
console.log('WARNING: found non-hex characters', bad);
}
// split the string into pairs of octets
var pairs = hexString.match(/[\dA-F]{2}/gi);
// convert the octets to integers
var integers = pairs.map(function(s) {
return parseInt(s, 16);
});
var array = new Uint8Array(integers);
console.log(array);
return array.buffer;
}
let arrv=hexStringToArrayBuffer("<?=$hex?>");
var string = new TextDecoder().decode(arrv);//arraybuffer转字符串
console.log(string);
var code = ('回').charCodeAt(0);
// 1110xxxx
var byte1 = 0xE0 | ((code >> 12) & 0x0F);
// 10xxxxxx
var byte2 = 0x80 | ((code >> 6) & 0x3F);
// 10xxxxxx
var byte3 = 0x80 | (code & 0x3F);
console.group('Test chr: ');
console.log("UTF-8编码:", byte1.toString(16).toUpperCase() + '' + byte2.toString(16).toUpperCase() + '' + byte3.toString(16).toUpperCase());
console.log("Unicode编码: ", code);
console.groupEnd();
</script>
网友回复