代码之家  ›  专栏  ›  技术社区  ›  CPHPython

PHP:如何匹配一系列unicode配对的代理emoticons/emoji?

  •  0
  • CPHPython  · 技术社区  · 7 年前

    anubhava 's answer about matching ranges of unicode characters 引导我使用regex清理特定范围的单个代码点字符。有了它,现在我可以匹配所有 miscellaneous symbols in this list (包括表情符号)使用此简单表达式:

    preg_replace('/[\x{2600}-\x{26FF}]/u', '', $str);
    

    不过,我也希望能在这个 list of paired/double surrogates emoji nhahtdh explained in a comment :

    有一个范围 d800 dfff 在UTF-16中指定代理项以允许指定更多字符。一个 指定有效字符)。

    preg_replace('/\x{D83D}\x{DE00}/u', '', $str);
    

    只替换第一个 paired surrogates on this list ,即:

    PHP抛出:

    preg_replace() :编译失败:不允许的Unicode代码点 (>= 0xd800 && <= 0xdfff)

    我尝试了几种不同的组合,包括上面的代码点在 UTF8 for 😀 ( '/[\x{00F0}\x{009F}\x{0098}\x{0080}]/u' ),但我仍然无法与之匹配。我还调查了其他 PCRE pattern modifiers u 是唯一允许指向UTF8的。

    我是不是错过了什么“逃跑”的选择?

    1 回复  |  直到 7 年前
        1
  •  4
  •   CPHPython    7 年前

    revo's comment above 很有助于找到解决方案:

    如果您的PHP没有附带用于UTF-16的PCRE构建,那么您就不能执行这样的匹配。 从PHP 7.0开始 \u{XXXX} 例如 preg_replace("~\u{1F600}~", '', $str); (注意 )

    因为我使用的是PHP 7, echo "\u{1F602}"; PHP RFC page on unicode escape . 这项提议的实质是:

    为添加了新的转义序列 双引号字符串 还有埃雷多克。

    • \u{ codepoint-digits } 哪里 codepoint-digits

    这意味着 preg_replace (通常是单引号,因为没有弄乱双引号字符串变量扩展),现在需要一些 preg_quote magic . 这就是我想出的解决办法:

    preg_replace(
      // single point unicode list
      "/[\x{2600}-\x{26FF}".
      // http://www.fileformat.info/info/unicode/block/miscellaneous_symbols/list.htm
      // concatenates with paired surrogates
      preg_quote("\u{1F600}", '/')."-".preg_quote("\u{1F64F}", '/').
      // https://www.fileformat.info/info/unicode/block/emoticons/list.htm
      "]/u",
      '',
      $str
    );
    

    这是 proof of the above in 3v4l .

    another comment made by revo

    preg_replace('/[☀-⛿😀-🙏]/u','YOINK',$str);
    

    供使用 PHP 7's new feature though

    preg_replace("/[\u{2600}-\u{26FF}\u{1F600}-\u{1F64F}]/u",'YOINK',$str);
    

    这是 revo's proof in 3v4l .