Skip to content
Advertisement

How to pass slashes in Elasticsearch query using PHP?

Below mentioned elastic search query which is working fine if we hit it directly,

{
 "query": {
    "query_string": {
        "query": ""testtext/123""
    }
 }
}

In PHP array how to pass the above-mentioned query with backslashes. I tried the below code which gives an error response.

$query = array(
  "query"=>[
    "query_string"=> [
      "query"=>"".$string.""
    ]
  ]
);

Error is:

syntax error, unexpected ” (T_NS_SEPARATOR)

Advertisement

Answer

is an escape character, you need to escape that itself otherwise it escapes the second " so PHP thinks the strings are unfinished. You need to resolve the syntax error and also ensure the the second quote mark is actually part of the string, not a PHP delimiter.

The simplest way actually would be to use single quotes for the string delimiter in PHP:

$query = array(
  "query"=>[
    "query_string"=> [
      "query"=>'"'.$string.'"'
    ]
  ]
);
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement