duanmeng2842 2019-04-12 09:08
浏览 254
已采纳

将\ u表情符号字符串转换为电子邮件正文的utf-8

I am having the following emoji in a PHP string variable

$emoji = "\u{1F9D1}\u{1F4AC}";
echo $emoji;

This code above will print the following emoji.

  • 写回答

1条回答 默认 最新

  • dqbhdsec59405 2019-04-12 09:14
    关注
    $foo = preg_replace('#\\\u\{(.*?)\}#', '&#x$1;', $emoji);
    
    • \u needs to be escaped because it has special meaning in a regular expression, and since the backslash also has special meaning in PHP text literals, we need three of them here.

    • { and } also have special meaning, so they need to get escaped with a single backslash.

    • (.*?) matches everything (expect newlines), ? makes it ungreedy.

    • I added an ; at the end in the replacement - browsers are fault tolerant when it’s missing, but it is technically required by HTML syntax.


    And the “other direction”, as requested:

    $emojihtml = '🧑💬';
    
    $bar = preg_replace('~&#x(.*?);~', '\u{$1}', $emojihtml);
    

    (I used ~ for the regex delimiters here, because # is part of what we want to match, saves on escaping.)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?