Inspired by node-elasticsearch-sanitize
Accepts an arbitrary string as input and escapes the ElasticSearch reserved characters:
+ - = && || > < ! ( ) { } [ ] ^ " ~ * ? : \ / AND OR NOT space
Returns a sanitized string which can be safely used in an ElasticSearch query_string query.
The preferred way to install this extension is through composer.
Either run
composer require sspat/es-query-sanitizer
or add
"sspat/es-query-sanitizer": "~1.0"
to the require section of your composer.json
file.
To use pass in a string:
$unescapedQueryString = 'AND there! are? (lots of) char*cters 2 ^escape!'
$escapedQueryString = \sspat\ESQuerySanitizer\Sanitizer::escape($unescapedQueryString);
echo $escapedQueryString; // \A\N\D\ there\!\ are\?\ \(lots\ of\)\ char\*cters\ 2\ \^escape\!
You can also pass an array as the second argument, if you want to prevent some characters from being escaped:
$unescapedQueryString = 'AND there! are? (lots of) char*cters 2 ^escape!'
$excludeCharacters = ['!', '^'];
$escapedQueryString = \sspat\ESQuerySanitizer\Sanitizer::escape($unescapedQueryString, $excludeCharacters);
echo $escapedQueryString; // \A\N\D\ there!\ are\?\ \(lots\ of\)\ char\*cters\ 2\ ^escape!