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

标签 php regex word-boundary

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

$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)

我该如何解决?

最佳答案

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

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

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

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

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

关于php - 为什么\b 对于某些语言不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671418/

相关文章:

javascript - 在复选框更改时更新数据库字段 - AJAX

Python Regex - 查找单词中的字符串模式

c# - 当单词以方括号等特殊字符开头或结尾时,单词边界不匹配

regex - VIM - 当前缓冲区中视觉选择的 VIMGREP 热键

javascript - 正则表达式来匹配这组值

javascript - 如何制作考虑重音字符的正则表达式?

regex - 正则表达式以匹配不同Unicode脚本之间的边界

php - csv 字段匹配在 where

php - 比较两个用户定义对象数组

PHP:无法执行()wkhtmltopdf: "sh:/usr/bin/wkhtmltopdf: Permission denied"