在PHP中转义elasticsearch特殊字符

wjh*_*sch 5 php regex elasticsearch

我想创建一个函数,通过在PHP中的字符之前添加\来转义elasticsearch特殊字符.Elasticsearch使用的特殊字符是:+ - = && || > <!(){} [] ^"〜*?:\ /

我对正则表达式不是很熟悉,但是我发现了一段代码,它只是删除了特殊的字符,但我更愿意逃避它们,因为它可能是相关的.我使用的代码:

$s_input = 'The next chars should be escaped: + - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ / Did it work?';
$search_query = preg_replace('/(\+|\-|\=|\&|\||\!|\(|\)|\{|\}|\[|\]|\^|\"|\~|\*|\<|\>|\?|\:|\\\\)/', '', $s_input);
Run Code Online (Sandbox Code Playgroud)

这输出:

The next chars should be escaped / Did it work
Run Code Online (Sandbox Code Playgroud)

所以有两个问题:这个代码删除了特殊的字符,而我想用它来转义它们\.此外:这段代码没有逃脱\.有谁知道如何逃避Elasticsearch特殊字符?

Lou*_*iro 6

你可以使用带有反向引用的preg_match,因为stribizhev已经注意到了它(最简单的方法):

$string = "The next chars should be escaped: + - = && || > < ! ( ) { } [ ] ^ \" ~ * ? : \ / Did it work?"; 

function escapeElasticReservedChars($string) {
    $regex = "/[\\+\\-\\=\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\*\\<\\>\\?\\:\\\\\\/]/";
    return preg_replace($regex, addslashes('\\$0'), $string);
}
echo escapeElasticReservedChars($string);
Run Code Online (Sandbox Code Playgroud)

或使用preg_match_callback函数来实现.感谢回调,您将能够获得当前匹配并进行编辑.

将调用并在主题字符串中传递匹配元素数组的回调.回调应该返回替换字符串.这是回调签名:

这是在行动:

<?php 
$string = "The next chars should be escaped: + - = && || > < ! ( ) { } [ ] ^ \" ~ * ? : \ / Did it work?"; 

function escapeElasticSearchReservedChars($string) {
    $regex = "/[\\+\\-\\=\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\*\\<\\>\\?\\:\\\\\\/]/";
    $string = preg_replace_callback ($regex, 
        function ($matches) { 
            return "\\" . $matches[0]; 
        }, $string); 
    return $string;
}
echo escapeElasticSearchReservedChars($string);
Run Code Online (Sandbox Code Playgroud)

输出: The next chars should be escaped\: \+ \- \= \&\& \|\| \> \< \! \( \) \{ \} \[ \] \^ \" \~ \* \? \: \\ \/ Did it work\?