【问题标题】:How to detect 4-byte characters using PHP如何使用 PHP 检测 4 字节字符
【发布时间】:2020-02-28 09:57:00
【问题描述】:

我需要帮助来使用 PHP 检测字符串何时包含 4 字节字符。是否有内置函数或正则表达式可以有效地做到这一点?

我找到了这篇关于替换的文章,但我找不到一个可以检测到的工作示例。

Can php detect 4-byte encoded utf8 chars?

这大约是我得到的,但它也失败了:

$chars = str_split($term);
foreach ($chars as $char) {
    if (strlen($char) >= 4) {
        print "Found 4-byte character\n";
    }
}

【问题讨论】:

  • str_split 将拆分字节,而不是字符
  • 检测到它们后你想做什么?删除、计数、收集成数组?
  • @Dharman 使用它从列表中删除关键字。

标签: php unicode


【解决方案1】:

可以使用正则匹配BMP以外的所有字符,即U+FFFF以上Unicode空间中的所有字符

$str = '€?A?¢';

$r = preg_match_all('|[\x{10000}-\x{10FFFF}]|u', $str, $matches);

var_dump($matches[0]);

在这里试试:https://3v4l.org/JX9aQ

有趣的事实。如果您使用的是 PHP 7.4,您可以使用 mb_str_split()array_filter() 来做到这一点。我认为它不会比正则表达式更有效,但很高兴知道。

$nonBMP = array_filter(mb_str_split($str), fn($c) => strlen($c)==4);

【讨论】:

    【解决方案2】:

    如果您使用的是 utf8 字符,则必须使用多字节字符串函数。这些函数允许您显示字符串中每个字符的字节数,类似于您的代码:

    $string = '€?A?¢';
    for($i=0; $i < mb_strlen($string); $i++){
      $mbChar = mb_substr($string,$i,1);
      echo $mbChar." (".strlen($mbChar)." Byte)<br>\n";
    }
    

    输出:

    € (3 Byte)
    ? (4 Byte)
    A (1 Byte)
    ? (4 Byte)
    ¢ (2 Byte)
    

    这个答案更便于理解。要查找 4 字节 UTF8 字符,@Dharman 所示的正则表达式更短且更快。

    【讨论】:

      猜你喜欢
      • 2013-04-01
      • 2013-09-12
      • 2020-08-08
      • 1970-01-01
      • 2012-09-20
      • 2014-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多