Elastica\Util::escapeTerm PHP Method

escapeTerm() public static method

Escapes the following terms (because part of the query language) + - && || ! ( ) { } [ ] ^ " ~ * ? : \ < >.
public static escapeTerm ( string $term ) : string
$term string Query term to escape
return string Escaped query term
    public static function escapeTerm($term)
    {
        $result = $term;
        // \ escaping has to be first, otherwise escaped later once again
        $chars = ['\\', '+', '-', '&&', '||', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '/', '<', '>'];
        foreach ($chars as $char) {
            $result = str_replace($char, '\\' . $char, $result);
        }
        return $result;
    }

Usage Example

Exemplo n.º 1
0
 /**
  * @param mixed  $query
  * @param string $lang
  * @param string $type
  *
  * @return mixed|void
  */
 public function defineSearch($query, $lang, $type)
 {
     $query = \Elastica\Util::escapeTerm($query);
     $elasticaQueryLang = new \Elastica\Query\Term();
     $elasticaQueryLang->setTerm('lang', $lang);
     $elasticaQueryString = new \Elastica\Query\Match();
     $elasticaQueryString->setFieldQuery('content', $query)->setFieldMinimumShouldMatch('content', '80%');
     $elasticaQueryTitle = new \Elastica\Query\QueryString();
     $elasticaQueryTitle->setDefaultField('title')->setBoost(2.0)->setQuery($query);
     $elasticaQueryBool = new \Elastica\Query\BoolQuery();
     $elasticaQueryBool->addMust($elasticaQueryLang)->addShould($elasticaQueryTitle)->addShould($elasticaQueryString)->setMinimumNumberShouldMatch(1);
     $this->applySecurityContext($elasticaQueryBool);
     if (!is_null($type)) {
         $elasticaQueryType = new \Elastica\Query\Term();
         $elasticaQueryType->setTerm('type', $type);
         $elasticaQueryBool->addMust($elasticaQueryType);
     }
     $rootNode = $this->domainConfiguration->getRootNode();
     if (!is_null($rootNode)) {
         $elasticaQueryRoot = new \Elastica\Query\Term();
         $elasticaQueryRoot->setTerm('root_id', $rootNode->getId());
         $elasticaQueryBool->addMust($elasticaQueryRoot);
     }
     $this->query->setQuery($elasticaQueryBool);
     $this->query->setHighlight(array('pre_tags' => array('<strong>'), 'post_tags' => array('</strong>'), 'fields' => array('content' => array('fragment_size' => 150, 'number_of_fragments' => 3))));
 }
All Usage Examples Of Elastica\Util::escapeTerm