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.)

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

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器