From 3d6bc54b66555cfc282702503b757c3186603f34 Mon Sep 17 00:00:00 2001 From: ghost Date: Mon, 31 Jul 2023 22:07:59 +0300 Subject: [PATCH] update Filter::searchQuery method --- library/filter.php | 58 ++++++++++++++++++++++++++++++---------------- 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/library/filter.php b/library/filter.php index 4e06b01..79721c7 100644 --- a/library/filter.php +++ b/library/filter.php @@ -79,34 +79,52 @@ class Filter { static public function searchQuery(string $query, string $mode = 'default') { + // Prepare user-friendly search request (default mode) + // https://sphinxsearch.com/docs/current.html#extended-syntax if ($mode == 'default') { - // Remove single char words - $words = []; - foreach ((array) explode(' ', $query) as $word) { + // Remove extra separators + $query = preg_replace('/[\s]+/', ' ', $query); - if (mb_strlen($word) > 1) { - $words[] = $word; - } - } - - if ($words) { - $query = implode(' ', $words); - } + $query = trim($query); - // Remove SphinxQL special chars - $query = str_replace(['\\', '/', '~', '@', '!', '"', '(', ')'], ['\\\\', '\/', '\~', '\@', '\!', '\"', '\(', '\)'], $query); + // Remove single char words + $words = []; + foreach ((array) explode(' ', $query) as $word) { - // Replace query separators to the MAYBE operator - $query = str_ireplace(['MAYBE'], ['__MAYBE__'], $query); - $query = preg_replace('/[\W\s]+/ui', '__SEPARATOR__', $query); - $query = trim($query, '__SEPARATOR__'); - $query = str_ireplace(['__SEPARATOR__', '__MAYBE__'], [' MAYBE ', ' \MAYBE '], $query); + if (mb_strlen($word) > 1) { + $words[] = $word; + } + } + + if ($words) { + $query = implode(' ', $words); + } + + // Quote reserved keyword operators + $operators = [ + 'MAYBE', + 'AND', + 'OR', + 'NOT', + 'SENTENCE', + 'NEAR', + 'ZONE', + 'ZONESPAN', + 'PARAGRAPH', + + '\\', '/', '~', '@', '!', '"', '(', ')', '|', '?', '%', '-', '>', '<', ':', ';' + ]; + + foreach ($operators as $operator) { + $query = str_ireplace($operator, '\\' . $operator, $query); + } } - $query = trim($query); + // Apply query semantics + $query = str_replace(' ', ' | ', $query); - return $query; + return trim($query); } static public function plural(int $number, array $texts) {