gpt4 book ai didi

php - 为什么 PHP 的 preg_split 在 “נ” 上拆分时将 UTF-8 中的希伯来字母 “\s” 拆分?

转载 作者:行者123 更新时间:2023-12-04 21:09:33 26 4
gpt4 key购买 nike

这行不通,它变成了乱码:

$foo = 'נ';
$bar = mb_convert_encoding($foo, 'UTF-8', mb_detect_encoding($foo));
print_r(preg_split('/\s/', $bar));

Array ( [0] => � [1] => )

但这行得通:

$foo = 'נ';
$bar = mb_convert_encoding($foo, 'ISO-8859-8', mb_detect_encoding($foo));
$baz = preg_split('/\s/', $bar);
echo(mb_convert_encoding($baz[0], 'UTF-8', 'ISO-8859-8'));

נ

问题仅出在字母“נ”上。它适用于所有其他希伯来字母。有解决方案吗?

最佳答案

使用 UTF-8 数据时,始终使用 u modifier在你的模式中:

/\s/u

否则模式不会被解释为 UTF-8。

在这种情况下,字符 נ (U+05E0) 在 UTF-8 中用 0xD7A0 编码。 \s 代表任何空白字符(根据 PCRE ):

The \s characters are HT (9), LF (10), FF (12), CR (13), and space (32).

当添加 UTF-8 支持时,他们还添加了一个名为 PCRE_UCP 的特殊选项以具有 \b\d\s\w 不仅匹配 US-ASCII 字符,还匹配其他 Unicode 字符的 Unicode 属性:

By default, in UTF-8 mode, characters with values greater than 128 never match \d, \s, or \w, and always match \D, \S, and \W. […] However, if PCRE is compiled with Unicode property support, and the PCRE_UCP option is set, the behaviour is changed so that Unicode properties are used to determine character types, as follows:

  • \d any character that \p{Nd} matches (decimal digit)
  • \s any character that \p{Z} matches, plus HT, LF, FF, CR
  • \w any character that \p{L} or \p{N} matches, plus underscore

并且不间断空格 U+00A0 具有分隔符的属性 (\p{Z})。

因此,虽然您的模式不是 UTF-8 模式,但似乎 \s 确实 匹配 UTF-8 代码字 0xD7A0 中的 0xA0,拆分字符串在该位置并返回等效于 array("\xD7", "") 的数组。

这显然是一个错误,因为模式在 UTF-8 模式下但 0xA0 大于 0x80(此外,0xA0 将被编码为 0xC2A0)。 bug #52971 PCRE-Meta-Characters not working with utf-8可能与此有关。

关于php - 为什么 PHP 的 preg_split 在 “נ” 上拆分时将 UTF-8 中的希伯来字母 “\s” 拆分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4231864/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com