4

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

$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对波斯语不起作用:(它总是返回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)

我该如何解决?

4

2 回答 2

4

你已经把你的正则表达式放在一个字符类中,从中"/[\b(?:دیوار|خوب)\b]/u"删除:[]

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

您可以替换为\b

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

您还可以\s使用列出阿拉伯字母的否定字符类来更改 。我不认识他们,但就像:[^دیوارخوب]...

于 2015-11-12T12:36:09.930 回答
1

字符类\b内部或双引号正则表达式内部是退格字符。

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

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

请参阅此IDEONE 演示

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)
于 2015-11-12T14:52:54.523 回答