Escape elasticsearch special characters in PHP
You can use preg_match with backreferences as stribizhev has noticed it (simpliest way) :
$string = "The next chars should be escaped: + - = && || > < ! ( ) { } [ ] ^ \" ~ * ? : \ / Did it work?";
function escapeElasticReservedChars($string) {
$regex = "/[\\+\\-\\=\\&\\|\\!\\(\\)\\{\\}\\[\\]\\^\\\"\\~\\*\\<\\>\\?\\:\\\\\\/]/";
return preg_replace($regex, addslashes('\\$0'), $string);
}
echo escapeElasticReservedChars($string);
or use preg_match_callback function to achieve that. Thank to the callback, you will be able to have the current match and edit it.
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:
Here is in action :
<?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);
Output: The next chars should be escaped\: \+ \- \= \&\& \|\| \> \< \! \( \) \{ \} \[ \] \^ \" \~ \* \? \: \\ \/ Did it work\?