如何在Jenssegers的raw()函数中正确应用正则表达式

4
我尝试在自己的应用中实现一个不区分发音符号的全词搜索。我编写了以下查询,在MongoDB终端(我使用Robo3T)中工作正常。
[ 这里我传递了单词 'Irène' 的Unicode转换 ]
db.getCollection('rvh_articles').aggregate([
  {
    "$match":{
       "art_xml_data.article.article_title":{
          "$regex":/( |^)[i\x{00ec}\x{00ed}\x{00ee}\x{00ef}]r[e\x{00e8}\x{00e9}\x{00ea}\x{00eb}\x{00e6}][n\x{00f1}][e\x{00e8}\x{00e9}\x{00ea}\x{00eb}\x{00e6}]( |$)/,
          "$options":"I"
       }
    }
  }
])

当我尝试在jenssegers raw()函数中实现此查询时,我编写了一个PHP函数来构建与搜索字符串相对应的正则表达式。该函数将把字符串中的每个字母转换为相应的Unicode并返回正则表达式。
public function makeComp($input) 
{
    $accents = array(
        /*
            I include json_encode here because:
            json_encode used in the jenssegers building query function converts diacritic charectes to 
            hexadecimal(\u). But '\u' is not supported with regex mongodb. It shows this error:
            "Regular expression is invalid: PCRE does not support \\L, \\l, \\N{name}, \\U, or \\u"

            So I first used json_encode for each string conversion and then replaced '{\u' with '{\x'. Problem solved.
        */
        "a" => json_encode('[a{à}{á}{â}{ã}{ä}{å}{æ}]'),
        "c" => json_encode('[c{ç}]'),
        "e" => json_encode('[e{è}{é}{ê}{ë}{æ}]'),
        "i" => json_encode('[i{ì}{í}{î}{ï}]'),
        "n" => json_encode('[n{ñ}]'),
        "o" => json_encode('[o{ò}{ó}{ô}{õ}{ö}{ø}]'),
        "s" => json_encode('[s{ß}]'),
        "u" => json_encode('[u{ù}{ú}{û}{ü}]'),
        "y" => json_encode('[y{ÿ}]'),
    );
    $out = strtr($input, $accents); // replacing all possible accented characters in the input string with $accents array key value
    $out = str_replace('{\u', '\x{', $out); // replace all {\u to \x{ because PCRE does not support the \uXXXX syntax. Use \x{XXXX}.
    $out = str_replace('"', "", $out); // replace all double quotes
    return '/( |^)' . $out . '( |$)/';
}

这是我在jenssegers的raw()函数中应用MongoDB查询的函数。

public function getall_articles(Request $request)
{
    extract($request->all());

    if (!empty($search_key)) {
        DB::connection()->enableQueryLog();

        $search_key = $this->makeComp($search_key);

        $data = Article::raw()->aggregate([
            array(
                '$match' => array(
                    "art_xml_data.article.article_title" => array(
                        '$regex' => $search_key,
                        '$options' => 'i'
                    )
                )
            )
        ])->toArray();

        dd(DB::getQueryLog());
    }
}

这是打印的查询日志:
array:1 [
    0 => array:3 [
        "query" => rvh_articles.aggregate([{
            "$match":{
                "art_xml_data.article.article_title":{
                    "$regex":"\/( |^)[i\\x{00ec}\\x{00ed}\\x{00ee}\\x{00ef}]r[e\\x{00e8}\\x{00e9}\\x{00ea}\\x{00eb}\\x{00e6}][n\\x{00f1}][e\\x{00e8}\\x{00e9}\\x{00ea}\\x{00eb}\\x{00e6}]( |$)\/",
                    "$options":"i"
                }
            }
        }])
        "bindings" => []
        "time" => 620.14
    ]
]

我应用的正则表达式没有放置在正确位置,所以MongoDB返回了零结果。有人可以帮我解决这个问题吗? 我需要另一种解决方案来使用jenssegers的raw()函数进行忽略音符和大小写搜索。


2
如果你移除掉 /,会怎么样呢?return '( |^)' . $out . '( |$)';,或者甚至是 return '(?<!\S)' . $out . '(?!\S)'; - Wiktor Stribiżew
1
@WiktorStribiżew 这是查询日志中去除 '/' 后的正则表达式部分: {"$regex":"( |^)[i\x{00ec}\x{00ed}\x{00ee}\x{00ef}]r[e\x{00e8}\x{00e9}\x{00ea}\x{00eb}\x{00e6}][n\x{00f1}]e\x{00e8}\x{00e9}\x{00ea}\x{00eb}\x{00e6}"} - Anoop Sankar
2
@WiktorStribiżew 这个更改很好用。return '(?<!\S)' . $out . '(?!\S)';。非常感谢。你能把这个作为答案吗?这样我就可以标记了。 - Anoop Sankar
1个回答

2
在你的public function makeComp($input)方法中,你需要使用
return '(?<!\S)' . $out . '(?!\S)';

如果$out可能(在未来)包含用|分隔的多个备选项,则应该将模式分组。
return '(?<!\S)(?:' . $out . ')(?!\S)';
#              ^^^            ^

请注意,(?<!\S) 是一个左侧空格边界,它匹配的位置不会立即前面跟着非空格字符,而 (?!\S) 是一个右侧空格边界,它匹配的位置不会立即后面跟着非空格字符。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接