使用 PHP 將 Unicode 字元轉換為 uxxxx 格式

你可以使用以下程式碼返回和轉發。

if (!function_exists('codepoint_encode')) {
    function codepoint_encode($str) {
        return substr(json_encode($str), 1, -1);
    }
}

if (!function_exists('codepoint_decode')) {
    function codepoint_decode($str) {
        return json_decode(sprintf('"%s"', $str));
    }
}

使用方法

echo "\nUse JSON encoding / decoding\n";
var_dump(codepoint_encode("我好"));
var_dump(codepoint_decode('\u6211\u597d'));

輸出

Use JSON encoding / decoding
string(12) "\u6211\u597d"
string(6) "我好"