为什么 \b 对于某些语言不能正常工作?

Why \b does not work correctly for some languages?

这是我的代码:(它适用于英语语言)

$str1 = "itt is a testt";
$str2 = "it is a testt";
$str3 = "itt is a test";
$str4 = "it is a test";

echo preg_match("[\b(?:it|test)\b]", $str1) ? 1 : 2; // output: 2 (do not match)
                                     $str2           // output: 1 (it matches)
                                     $str3           // output: 1 (it matches)
                                     $str4           // output: 1 (it matches)

但我不知道为什么,上面的 REGEX 对于波斯语不能正常工作:(它总是 returns 1

$str1 = "دیوار";
$str2 = "دیوارر";

echo preg_match("/[\b(?:دیوار|خوب)\b]/u", $str1) ? 1 : 2; // output: 1
echo preg_match("/[\b(?:دیوار|خوب)\b]/u", $str2) ? 1 : 2; // output: 1 (it should be 2)

我该如何解决?

您已将正则表达式放入 "/[\b(?:دیوار|خوب)\b]/u" 中的字符 class,从中删除 []

"/\b(?:دیوار|خوب)\b/u"

您可以用替代方法替换 \b

"/(?:^|\s)(?:دیوار|خوب)(?:\s|$)/u"

您还可以将 \s 更改为包含阿拉伯字母的否定字符 class。我不认识他们,但就像:[^دیوارخوب]...

字符 class 或双引号正则表达式中的 \bbackspace 字符。

这就是为什么正确答案是:要么使用单引号正则表达式声明以免使用双转义,要么在双引号正则表达式中的 b 之前使用双反斜杠。

  • '/\b(?:دیوار|خوب)\b/u' 或...
  • "/\b(?:دیوار|خوب)\b/u"

看到这个IDEONE demo:

echo preg_match('/\b(?:دیوار|خوب)\b/u', $str1) ? 1 : 2; // output: 1
echo preg_match('/\b(?:دیوار|خوب)\b/u', $str2) ? 1 : 2; // output: 1 (it should be 2)