How to convert text to unicode code point like \u0054\u0068\u0069\u0073 using php?

后端 未结 1 1300
情深已故
情深已故 2020-12-18 15:14

EDIT 2: I\'d like to convert English words to unicode numbers using php5 and then produced as \\u* * * * where * * * * is the unicode number.

<
相关标签:
1条回答
  • 2020-12-18 15:53

    json_encode pretty much does it for you, but only for non-ASCII characters. So all you need to do is to convert ASCII characters by hand. Here's a function that does that on a character-by-character basis:

    function utf8ToUnicodeCodePoints($str) {
        if (!mb_check_encoding($str, 'UTF-8')) {
            trigger_error('$str is not encoded in UTF-8, I cannot work like this');
            return false;
        }
        return preg_replace_callback('/./u', function ($m) {
            $ord = ord($m[0]);
            if ($ord <= 127) {
                return sprintf('\u%04x', $ord);
            } else {
                return trim(json_encode($m[0]), '"');
            }
        }, $str);
    }
    
    0 讨论(0)
提交回复
热议问题