5 * This represents "Google-like" text search queries like:
8 * <dd> Match strings containing the substring 'wiki', and not containing the
10 * <dt> wiki word or page
11 * <dd> Match strings containing the substring 'wiki' and either the substring
12 * 'word' or the substring 'page'.
15 * The full query syntax, in order of precedence, is roughly:
17 * The unary 'NOT' or '-' operator (they are equivalent) negates the
18 * following search clause.
20 * Search clauses may be joined with the (left-associative) binary operators
23 * Two adjoining search clauses are joined with an implicit 'AND'. This has
24 * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
25 * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
26 * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
28 * Search clauses can be grouped with parentheses.
30 * Phrases (or other things which don't look like words) can be forced to
31 * be interpreted as words by quoting them, either with single (') or double (")
32 * quotes. If you wan't to include the quote character within a quoted string,
33 * double-up on the quote character: 'I''m hungry' is equivalent to
36 class TextSearchQuery {
40 * @param $search_query string The query. Syntax is as described above.
41 * Note that an empty $search_query will match anything.
42 * @see TextSearchQuery
44 function TextSearchQuery($search_query) {
45 $parser = new TextSearchQuery_Parser;
46 $this->_tree = $parser->parse($search_query);
50 function _optimize() {
51 $this->_tree = $this->_tree->optimize();
55 * Get a regexp which matches the query.
58 if (!isset($this->_regexp))
59 $this->_regexp = '/^' . $this->_tree->regexp() . '/isS';
60 return $this->_regexp;
64 * Match query against string.
66 * @param $string string The string to match.
67 * @return boolean True if the string matches the query.
69 function match($string) {
70 return preg_match($this->asRegexp(), $string);
75 * Get a regular expression suitable for highlighting matched words.
77 * This returns a PCRE regular expression which matches any non-negated
80 * @return string The PCRE regexp.
82 function getHighlightRegexp() {
83 if (!isset($this->_hilight_regexp)) {
84 $words = array_unique($this->_tree->highlight_words());
86 $this->_hilight_regexp = false;
89 foreach ($words as $key => $word)
90 $words[$key] = preg_quote($word, '/');
91 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
94 return $this->_hilight_regexp;
98 * Make an SQL clause which matches the query.
100 * @param $make_sql_clause_func string,function or array
101 * A callback which takes a single word as an argument and
102 * returns an SQL clause which will match exactly those records
103 * containing the word. The word passed to the callback will always
104 * be in all lower case.
106 * If $make_sql_clause_func is an array, it is interpreted as a method
107 * callback. The first element of the array is the object, the second
108 * element (a string) is the name of the method.
110 * If $make_sql_clause_func is a string, it is taken to be the name
111 * of a global function to call.
113 * Otherwise, $make_sql_clause_func is assumed to be a function object
114 * (created by create_function()).
118 * function sql_title_match($word) {
119 * return sprintf("LOWER(title) like '%s'",
120 * addslashes($word));
125 * $query = new TextSearchQuery("wiki -page");
126 * $sql_clause = $query->makeSqlClause('sql_title_match');
128 * This will result in $sql_clause containing something like
129 * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
131 * @return string The PCRE regexp.
133 function makeSqlClause($make_sql_clause_func) {
134 $this->_sql_clause_func = $make_sql_clause_func;
135 return $this->_sql_clause($this->_tree);
138 function _sql_clause($node) {
141 $callback = $this->_sql_clause_func;
142 if (is_array($callback)) {
143 list($object, $method) = $callback;
144 return call_user_method($method, $object, $node->word);
146 elseif (is_string($callback))
147 return call_user_func($callback, $node->word);
149 return $callback($node->word);
151 return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
154 $subclauses = array();
155 foreach ($node->leaves as $leaf)
156 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
157 return join(" $node->op ", $subclauses);
159 assert($node->op == 'VOID');
165 * Get printable representation of the parse tree.
167 * This is for debugging only.
168 * @return string Printable parse tree.
170 function asString() {
171 return $this->_as_string($this->_tree);
174 function _as_string($node, $indent = '') {
177 return $indent . "WORD: $node->word";
179 return $indent . "VOID";
181 $lines = array($indent . $node->op . ":");
183 foreach ($node->leaves as $leaf)
184 $lines[] = $this->_as_string($leaf, $indent);
185 return join("\n", $lines);
191 ////////////////////////////////////////////////////////////////
193 // Remaining classes are private.
195 ////////////////////////////////////////////////////////////////
197 * Virtual base class for nodes in a TextSearchQuery parse tree.
199 * Also servers as a 'VOID' (contentless) node.
201 class TextSearchQuery_node
206 * Optimize this node.
207 * @return object Optimized node.
209 function optimize() {
214 * @return regexp matching this node.
221 * @param bool True if this node has been negated (higher in the parse tree.)
222 * @return array A list of all non-negated words contained by this node.
224 function highlight_words($negated = false) {
232 class TextSearchQuery_node_word
233 extends TextSearchQuery_node
237 function TextSearchQuery_node_word($word) {
242 return '(?=.*' . preg_quote($this->word, '/') . ')';
245 function highlight_words($negated = false) {
246 return $negated ? array() : array($this->word);
254 class TextSearchQuery_node_not
255 extends TextSearchQuery_node
259 function TextSearchQuery_node_not($leaf) {
260 $this->leaves = array($leaf);
263 function optimize() {
264 $leaf = &$this->leaves[0];
265 $leaf = $leaf->optimize();
266 if ($leaf->op == 'NOT')
267 return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
272 $leaf = &$this->leaves[0];
273 return '(?!' . $leaf->regexp() . ')';
276 function highlight_words($negated = false) {
277 return $this->leaves[0]->highlight_words(!$negated);
282 * Virtual base class for 'AND' and 'OR conjoins.
284 class TextSearchQuery_node_binop
285 extends TextSearchQuery_node
287 function TextSearchQuery_node_binop($leaves) {
288 $this->leaves = $leaves;
291 function _flatten() {
292 // This flattens e.g. (AND (AND a b) (OR c d) e)
293 // to (AND a b e (OR c d))
295 foreach ($this->leaves as $leaf) {
296 $leaf = $leaf->optimize();
297 if ($this->op == $leaf->op)
298 $flat = array_merge($flat, $leaf->leaves);
302 $this->leaves = $flat;
305 function optimize() {
307 assert(!empty($this->leaves));
308 if (count($this->leaves) == 1)
309 return $this->leaves[0]; // (AND x) -> x
313 function highlight_words($negated = false) {
315 foreach ($this->leaves as $leaf)
316 array_splice($words,0,0,
317 $leaf->highlight_words($negated));
323 * A (possibly multi-argument) 'AND' conjoin.
325 class TextSearchQuery_node_and
326 extends TextSearchQuery_node_binop
330 function optimize() {
333 // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
334 // Since OR's are more efficient for regexp matching:
335 // (?!.*a)(?!.*b) vs (?!.*(?:a|b))
337 // Suck out the negated leaves.
339 foreach ($this->leaves as $key => $leaf) {
340 if ($leaf->op == 'NOT') {
341 $nots[] = $leaf->leaves[0];
342 unset($this->leaves[$key]);
346 // Combine the negated leaves into a single negated or.
348 $node = ( new TextSearchQuery_node_not
349 (new TextSearchQuery_node_or($nots)) );
350 array_unshift($this->leaves, $node->optimize());
353 assert(!empty($this->leaves));
354 if (count($this->leaves) == 1)
355 return $this->leaves[0]; // (AND x) -> x
361 foreach ($this->leaves as $leaf)
362 $regexp .= $leaf->regexp();
368 * A (possibly multi-argument) 'OR' conjoin.
370 class TextSearchQuery_node_or
371 extends TextSearchQuery_node_binop
376 // We will combine any of our direct descendents which are WORDs
377 // into a single (?=.*(?:word1|word2|...)) regexp.
382 foreach ($this->leaves as $leaf) {
383 if ($leaf->op == 'WORD')
384 $words[] = preg_quote($leaf->word, '/');
386 $regexps[] = $leaf->regexp();
390 array_unshift($regexps,
391 '(?=.*' . $this->_join($words) . ')');
393 return $this->_join($regexps);
396 function _join($regexps) {
397 assert(count($regexps) > 0);
399 if (count($regexps) > 1)
400 return '(?:' . join('|', $regexps) . ')';
407 ////////////////////////////////////////////////////////////////
411 ////////////////////////////////////////////////////////////////
412 define ('TSQ_TOK_WORD', 1);
413 define ('TSQ_TOK_BINOP', 2);
414 define ('TSQ_TOK_NOT', 4);
415 define ('TSQ_TOK_LPAREN', 8);
416 define ('TSQ_TOK_RPAREN', 16);
418 class TextSearchQuery_Parser
421 * This is a simple recursive descent parser, based on the following grammar:
436 * atom : '(' list ')'
441 * The terminal tokens are:
448 * [^-()\s][^()\s]* WORD
453 function parse ($search_expr) {
454 $this->lexer = new TextSearchQuery_Lexer($search_expr);
455 $tree = $this->get_list('toplevel');
456 assert($this->lexer->eof());
461 function get_list ($is_toplevel = false) {
464 // token types we'll accept as words (and thus expr's) for the
465 // purpose of error recovery:
466 $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
468 $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
470 while ( ($expr = $this->get_expr())
471 || ($expr = $this->get_word($accept_as_words)) ) {
478 return new TextSearchQuery_node;
482 return new TextSearchQuery_node_and($list);
485 function get_expr () {
486 if ( !($expr = $this->get_atom()) )
489 $savedpos = $this->lexer->tell();
490 while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
491 if ( ! ($right = $this->get_atom()) ) {
496 $expr = new TextSearchQuery_node_and(array($expr, $right));
499 $expr = new TextSearchQuery_node_or(array($expr, $right));
502 $savedpos = $this->lexer->tell();
504 $this->lexer->seek($savedpos);
510 function get_atom() {
511 if ($word = $this->get_word())
514 $savedpos = $this->lexer->tell();
515 if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
516 if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
519 elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
520 if ( ($atom = $this->get_atom()) )
521 return new TextSearchQuery_node_not($atom);
523 $this->lexer->seek($savedpos);
527 function get_word($accept = TSQ_TOK_WORD) {
528 if ( ($word = $this->lexer->get($accept)) )
529 return new TextSearchQuery_node_word($word);
534 class TextSearchQuery_Lexer {
535 function TextSearchQuery_Lexer ($query_str) {
536 $this->tokens = $this->tokenize($query_str);
544 function seek($pos) {
549 return $this->pos == count($this->tokens);
552 function tokenize($string) {
554 $buf = strtolower(ltrim($string));
555 while (!empty($buf)) {
556 if (preg_match('/^(and|or)\s*/', $buf, $m)) {
558 $type = TSQ_TOK_BINOP;
560 elseif (preg_match('/^(-|not)\s*/', $buf, $m)) {
564 elseif (preg_match('/^([()])\s*/', $buf, $m)) {
566 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
568 elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
569 $val = str_replace('""', '"', $m[1]);
570 $type = TSQ_TOK_WORD;
572 elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
573 $val = str_replace("''", "'", $m[1]);
574 $type = TSQ_TOK_WORD;
576 elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
578 $type = TSQ_TOK_WORD;
584 $buf = substr($buf, strlen($m[0]));
585 $tokens[] = array($type, $val);
590 function get($accept) {
591 if ($this->pos >= count($this->tokens))
594 list ($type, $val) = $this->tokens[$this->pos];
595 if (($type & $accept) == 0)
607 // c-hanging-comment-ender-p: nil
608 // indent-tabs-mode: nil