gpt4 book ai didi

php - 在 PHP 中转义 elasticsearch 特殊字符

转载 作者:可可西里 更新时间:2023-11-01 14:01:15 24 4
gpt4 key购买 nike

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

我不是很熟悉正则表达式,但我找到了一段代码,它只是删除了特殊字符,但我更喜欢转义它们,因为它们可能是相关的。我使用的代码:

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

这个输出:

The next chars should be escaped / Did it work

所以有两个问题:这段代码删除了特殊字符,而我想用 \ 转义它们。此外:此代码不会转义 \。有谁知道如何转义 Elasticsearch 特殊字符?

最佳答案

您可以使用 preg_match使用 backreferences 作为 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);

或使用 preg_match_callback功能来实现这一点。感谢回调,您将能够获得当前匹配项并对其进行编辑。

A callback that will be called and passed an array of matched elements in the subject string. The callback should return the replacement string. This is the callback signature:

这是实际操作:

<?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);

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

关于php - 在 PHP 中转义 elasticsearch 特殊字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33845230/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com