public static function encodeMb4(string $string): string
    {
        // Does this string have any 4+ byte Unicode chars?
        if (max(array_map('ord', str_split($string))) >= 240) {
            $string = preg_replace_callback('/./u', function (array $match) {
                if (strlen($match[0]) >= 4) {
                    // (Logic pulled from WP's wp_encode_emoji() function)
                    // UTF-32's hex encoding is the same as HTML's hex encoding.
                    // So, by converting from UTF-8 to UTF-32, we magically
                    // get the correct hex encoding.
                    $unpacked = unpack('H*', mb_convert_encoding($match[0], 'UTF-32', 'UTF-8'));

                    return isset($unpacked[1]) ? '&#x' . ltrim($unpacked[1], '0') . ';' : '';
                }

                return $match[0];
            }, $string);
        }

        return $string;
    }