【问题标题】:Extract \ud83d\ude1b\ud83d\ude44 emoji string from a a given string:从给定字符串中提取 \ud83d\ude1b\ud83d\ude44 表情符号字符串:
【发布时间】:2016-08-30 09:41:43
【问题描述】:

我有一个类似的字符串:-

Hi, Jax\ud83d\ude1b\ud83d\ude44! can we go for a coffee?

现在,表情符号是 UTF16(我认为)。我需要提取 '\ud83d\ude1b\ud83d\ude44' 并在每对之间留一个空格,就像这样。

Hi, Jax\ud83d\ude1b \ud83d\ude44! can we go for a coffee?

如何在 PHP 中实现这一点?

我需要的更多示例:-

Hi, Jax\ud83d\ude1b \ud83d\ude44! can we go for\ud83d\ude1b \ud83d\ude44 a coffee?

那么需要做什么:-

  1. 用户可能会或可能不会在任何普通单词后留下任何空格,只需输入表情符号即可。我的意思是,Jax\ud83d\ude1bJax \ud83d\ude1b
  2. 表情符号可能总是不同,因为它们来自 DB。如何将每个表情符号模式拆分成对?

【问题讨论】:

  • 一种天真的方法:str_replace("\ud83d\ude1b\ud83d\ude44", "\ud83d\ude1b \ud83d\ude44", $s).
  • @WiktorStribiżew,它还需要提取字符串中的每个表情符号。字符串正在生成动态。所以表情符号模式,字符串模式可能会有所不同。
  • `Jax` 是表情符号字符串的一部分吗?
  • @protld。不,Jax 是一个普通的词(一个名字)。但是整个字符串是在“Jax”之后用表情符号保存的。没有空间。
  • 您可以使用((?:\\u[\da-fA-F]{4}){2}) 提取。 See regex101

标签: php regex unicode utf-16


【解决方案1】:

我不确定你想要什么,但这显示了如何(1)和(2)

$input = 'Hi, Jax\ud83d\ude1b\ud83d\ude44! can we go for a coffee?';

$pattern = '/((?:\\\\u[\dA-F]{4}){2})/i';
preg_match_all ( $pattern , $input , $mtchs); 
print_r($mtchs);

我真的不会 php,但是preg_match_all 将所有表情符号提取到一个数组中 - $mtchs (1)。

然后对于 (2),preg_replace 在它们之间插入一个空格,如果有背靠背的表情符号(或者更确切地说是*两个 unicode 字母后跟另一个开头 - \u)。

$pattern = '/((?:\\\\u[\dA-F]{4}){2})(\\\\u)/i';
print_r(preg_replace($pattern, '$1 $2', $input));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2021-01-29
    • 2016-05-26
    • 1970-01-01
    相关资源
    最近更新 更多