]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/TextSearchQuery.php
simpified regex search architecture:
[SourceForge/phpwiki.git] / lib / TextSearchQuery.php
1 <?php rcs_id('$Id: TextSearchQuery.php,v 1.12 2004-11-27 14:39:04 rurban Exp $');
2 /**
3  * A text search query, converting queries to PCRE or SQL matchers.
4  *
5  * This represents an enhanced "Google-like" text search query:
6  * <dl>
7  * <dt> default: case-insensitive glob-style search with special operators OR AND NOT -
8  * <dt> wiki -test
9  *   <dd> Match strings containing the substring 'wiki',  and not containing the
10  *        substring 'test'.
11  * <dt> wiki word or page
12  *   <dd> Match strings containing the substring 'wiki' and either the substring
13  *        'word' or the substring 'page'.
14  * <dt> detects regex hints, glob-style or regex-style, and converts them to PCRE or SQL matchers
15  *   <dd> "^word$" => EXACT(word)
16  *   <dd> "^word"  => STARTS_WITH(word)
17  *   <dd> "word*"  => STARTS_WITH(word)
18  *   <dd> "*word"  => ENDS_WITH(word)
19  *   <dd> "/^word.* /" => REGEX(^word.*)
20  *   <dd> "word*word" => REGEX(word.*word)
21  * </dl>
22  *
23  * The full query syntax, in order of precedence, is roughly:
24  *
25  * The unary 'NOT' or '-' operator (they are equivalent) negates the
26  * following search clause.
27  *
28  * Search clauses may be joined with the (left-associative) binary operators
29  * 'AND' and 'OR'.
30  *
31  * Two adjoining search clauses are joined with an implicit 'AND'.  This has
32  * lower precedence than either an explicit 'AND' or 'OR', so "a b OR c"
33  * parses as "a AND ( b OR c )", while "a AND b OR c" parses as
34  * "( a AND b ) OR c" (due to the left-associativity of 'AND' and 'OR'.)
35  *
36  * Search clauses can be grouped with parentheses.
37  *
38  * Phrases (or other things which don't look like words) can be forced to
39  * be interpreted as words by quoting them, either with single (') or double (")
40  * quotes.  If you wan't to include the quote character within a quoted string,
41  * double-up on the quote character: 'I''m hungry' is equivalent to
42  * "I'm hungry".
43  *
44  * Force regex on "re:word" => posix-style, "/word/" => pcre-style 
45  * or use regex='glob' to use file wildcard-like matching. (not yet)
46  *
47  * The parsed tree is then converted to the needed PCRE (highlight, simple backends) 
48  * or SQL functions. 
49  *
50  * @author: Jeff Dairiki
51  * @author: Reini Urban (case and regex detection, enhanced sql callbacks)
52  */
53
54 // regex-style: 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
55 define ('TSQ_REGEX_NONE', 0);
56 define ('TSQ_REGEX_AUTO', 1);
57 define ('TSQ_REGEX_POSIX', 2);
58 define ('TSQ_REGEX_GLOB', 4);
59 define ('TSQ_REGEX_PCRE', 8);
60 define ('TSQ_REGEX_SQL', 16);
61
62 class TextSearchQuery {
63     /**
64      * Create a new query.
65      *
66      * @param $search_query string The query.  Syntax is as described above.
67      * Note that an empty $search_query will match anything.
68      * @param $case_exact boolean
69      * @param $regex string one of 'auto', 'none', 'glob', 'posix', 'pcre', 'sql'
70      * @see TextSearchQuery
71      */
72     function TextSearchQuery($search_query, $case_exact=false, $regex='auto') {
73         if ($regex == 'none' or !$regex) 
74             $this->_regex = 0;
75         elseif (defined("TSQ_REGEX_".strtoupper($regex)))
76             $this->_regex = constant("TSQ_REGEX_".strtoupper($regex));
77         else {
78             trigger_error(fmt("Unsupported argument: %s=%s", 'regex', $regex));
79             $this->_regex = 0;
80         }
81         $this->_case_exact = $case_exact;
82         $parser = new TextSearchQuery_Parser;
83         $this->_tree = $parser->parse($search_query, $case_exact, $this->_regex);
84         $this->_optimize();
85     }
86
87     function _optimize() {
88         $this->_tree = $this->_tree->optimize();
89     }
90
91     /**
92      * Get a PCRE regexp which matches the query.
93      */
94     function asRegexp() {
95         if (!isset($this->_regexp)) {
96             if ($this->_regex)
97                 $this->_regexp =  '/' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
98             else
99                 $this->_regexp =  '/^' . $this->_tree->regexp() . '/'.($this->_case_exact?'':'i').'sS';
100         }
101         return $this->_regexp;
102     }
103
104     /**
105      * Match query against string.
106      *
107      * @param $string string The string to match. 
108      * @return boolean True if the string matches the query.
109      */
110     function match($string) {
111         return preg_match($this->asRegexp(), $string);
112     }
113
114     
115     /**
116      * Get a regular expression suitable for highlighting matched words.
117      *
118      * This returns a PCRE regular expression which matches any non-negated
119      * word in the query.
120      *
121      * @return string The PCRE regexp.
122      */
123     function getHighlightRegexp() {
124         if (!isset($this->_hilight_regexp)) {
125             $words = array_unique($this->_tree->highlight_words());
126             if (!$words) {
127                 $this->_hilight_regexp = false;
128             } else {
129                 foreach ($words as $key => $word)
130                     $words[$key] = preg_quote($word, '/');
131                 $this->_hilight_regexp = '(?:' . join('|', $words) . ')';
132             }
133         }
134         return $this->_hilight_regexp;
135     }
136
137     /**
138      * Make an SQL clause which matches the query. (deprecated, use makeSqlClause instead)
139      *
140      * @param $make_sql_clause_cb WikiCallback
141      * A callback which takes a single word as an argument and
142      * returns an SQL clause which will match exactly those records
143      * containing the word.  The word passed to the callback will always
144      * be in all lower case.
145      *
146      * TODO: support db-specific extensions, like MATCH AGAINST or REGEX
147      *       mysql => 4.0.1 can also do Google: MATCH AGAINST IN BOOLEAN MODE
148      *       How? WikiDB backend method?
149      *
150      * Old example usage:
151      * <pre>
152      *     function sql_title_match($word) {
153      *         return sprintf("LOWER(title) like '%s'",
154      *                        addslashes($word));
155      *     }
156      *
157      *     ...
158      *
159      *     $query = new TextSearchQuery("wiki -page");
160      *     $cb = new WikiFunctionCb('sql_title_match');
161      *     $sql_clause = $query->makeSqlClause($cb);
162      * </pre>
163      * This will result in $sql_clause containing something like
164      * "(LOWER(title) like 'wiki') AND NOT (LOWER(title) like 'page')".
165      *
166      * @return string The SQL clause.
167      */
168     function makeSqlClause($sql_clause_cb) {
169         $this->_sql_clause_cb = $sql_clause_cb;
170         return $this->_sql_clause($this->_tree);
171     }
172     // deprecated: use _sql_clause_obj now.
173     function _sql_clause($node) {
174         switch ($node->op) {
175         case 'WORD':        // word => %word%
176             return $this->_sql_clause_cb->call($node->word);
177         case 'NOT':
178             return "NOT (" . $this->_sql_clause($node->leaves[0]) . ")";
179         case 'AND':
180         case 'OR':
181             $subclauses = array();
182             foreach ($node->leaves as $leaf)
183                 $subclauses[] = "(" . $this->_sql_clause($leaf) . ")";
184             return join(" $node->op ", $subclauses);
185         default:
186             assert($node->op == VOID);
187             return '1=1';
188         }
189     }
190
191     /** Get away with the callback and use a db-specific search class instead.
192      * @see WikiDB_backend_PearDB_search
193      */
194     function makeSqlClauseObj(&$sql_search_cb) {
195         $this->_sql_clause_cb = $sql_search_cb;
196         return $this->_sql_clause_obj($this->_tree);
197     }
198
199     function _sql_clause_obj($node) {
200         switch ($node->op) {
201         case 'NOT':
202             return "NOT (" . $this->_sql_clause_cb->call($node->leaves[0]) . ")";
203         case 'AND':
204         case 'OR':
205             $subclauses = array();
206             foreach ($node->leaves as $leaf)
207                 $subclauses[] = "(" . $this->_sql_clause_obj($leaf) . ")";
208             return join(" $node->op ", $subclauses);
209         case 'VOID':
210             return '1=1';
211         default:
212             return $this->_sql_clause_cb->call($node);
213         }
214     }
215
216     /**
217      * Get printable representation of the parse tree.
218      *
219      * This is for debugging only.
220      * @return string Printable parse tree.
221      */
222     function asString() {
223         return $this->_as_string($this->_tree);
224     }
225
226     function _as_string($node, $indent = '') {
227         switch ($node->op) {
228         case 'WORD':
229             return $indent . "WORD: $node->word";
230         case 'VOID':
231             return $indent . "VOID";
232         default:
233             $lines = array($indent . $node->op . ":");
234             $indent .= "  ";
235             foreach ($node->leaves as $leaf)
236                 $lines[] = $this->_as_string($leaf, $indent);
237             return join("\n", $lines);
238         }
239     }
240 }
241
242 /**
243  * This is a TextSearchQuery which matches nothing.
244  */
245 class NullTextSearchQuery extends TextSearchQuery {
246     /**
247      * Create a new query.
248      *
249      * @see TextSearchQuery
250      */
251     function NullTextSearchQuery() {}
252     function asRegexp()         { return '/^(?!a)a/x'; }
253     function match($string)     { return false; }
254     function getHighlightRegexp() { return ""; }
255     function makeSqlClause($make_sql_clause_cb) { return "(1 = 0)"; }
256     function asString() { return "NullTextSearchQuery"; }
257 };
258
259
260 ////////////////////////////////////////////////////////////////
261 //
262 // Remaining classes are private.
263 //
264 ////////////////////////////////////////////////////////////////
265 /**
266  * Virtual base class for nodes in a TextSearchQuery parse tree.
267  *
268  * Also servers as a 'VOID' (contentless) node.
269  */
270 class TextSearchQuery_node
271 {
272     var $op = 'VOID';
273
274     /**
275      * Optimize this node.
276      * @return object Optimized node.
277      */
278     function optimize() {
279         return $this;
280     }
281
282     /**
283      * @return regexp matching this node.
284      */
285     function regexp() {
286         return '';
287     }
288
289     /**
290      * @param bool True if this node has been negated (higher in the parse tree.)
291      * @return array A list of all non-negated words contained by this node.
292      */
293     function highlight_words($negated = false) {
294         return array();
295     }
296 }
297
298 /**
299  * A word.
300  */
301 class TextSearchQuery_node_word
302 extends TextSearchQuery_node
303 {
304     var $op = "WORD";
305     
306     function TextSearchQuery_node_word($word) {
307         $this->word = $word;
308     }
309     function regexp() {
310         return '(?=.*' . preg_quote($this->word, '/') . ')';
311     }
312     function highlight_words($negated = false) {
313         return $negated ? array() : array($this->word);
314     }
315     function _sql_quote() {
316         $word = preg_replace('/(?=[%_\\\\])/', "\\", $this->word);
317         return $GLOBALS['request']->_dbi->qstr($word);
318     }
319     function sql()    { return '%'.$this->_sql_quote($this->word).'%'; }
320 }
321
322 class TextSearchQuery_node_starts_with
323 extends TextSearchQuery_node_word {
324     var $op = "STARTS_WITH";
325     function regexp() { return '(?=' . preg_quote($this->word, '/') . ')'; }
326     function sql()    { return $this->_sql_quote($this->word).'%'; }
327 }
328
329 class TextSearchQuery_node_ends_with
330 extends TextSearchQuery_node_word {
331     var $op = "ENDS_WITH";
332     function regexp() { return '(?=' . preg_quote($this->word, '/') . '.*)'; }
333     function sql()    { return '%'.$this->_sql_quote($this->word); }
334 }
335
336 class TextSearchQuery_node_exact
337 extends TextSearchQuery_node_word {
338     var $op = "EXACT";
339     function regexp() { return '(?=\B' . preg_quote($this->word, '/') . '\b)'; }
340     function sql()    { return $this->_sql_squote($this->word); }
341 }
342
343 class TextSearchQuery_node_regex // posix regex. FIXME!
344 extends TextSearchQuery_node_word {
345     var $op = "REGEX"; // using REGEXP or ~ extension
346     function regexp() { return '(?=\B' . $this->word . '\b)'; }
347     function sql()    { return $this->_sql_quote($this->word); }
348 }
349
350 class TextSearchQuery_node_regex_glob
351 extends TextSearchQuery_node_regex {
352     var $op = "REGEX_GLOB";
353     function regexp() { return '(?=\B' . glob_to_pcre($this->word) . '\b)'; }
354 }
355
356 class TextSearchQuery_node_regex_pcre // how to handle pcre modifiers? /i
357 extends TextSearchQuery_node_regex {
358     var $op = "REGEX_PCRE";
359     function regexp() { return $this->word; }
360 }
361
362 class TextSearchQuery_node_regex_sql
363 extends TextSearchQuery_node_regex {
364     var $op = "REGEX_SQL"; // using LIKE
365     function regexp() { return str_replace(array("/%/","/_/"), array(".*","."), $this->word); }
366     function sql()    { return $this->word; }
367 }
368
369 /**
370  * A negated clause.
371  */
372 class TextSearchQuery_node_not
373 extends TextSearchQuery_node
374 {
375     var $op = "NOT";
376     
377     function TextSearchQuery_node_not($leaf) {
378         $this->leaves = array($leaf);
379     }
380
381     function optimize() {
382         $leaf = &$this->leaves[0];
383         $leaf = $leaf->optimize();
384         if ($leaf->op == 'NOT')
385             return $leaf->leaves[0]; // ( NOT ( NOT x ) ) -> x
386         return $this;
387     }
388     
389     function regexp() {
390         $leaf = &$this->leaves[0];
391         return '(?!' . $leaf->regexp() . ')';
392     }
393
394     function highlight_words($negated = false) {
395         return $this->leaves[0]->highlight_words(!$negated);
396     }
397 }
398
399 /**
400  * Virtual base class for 'AND' and 'OR conjoins.
401  */
402 class TextSearchQuery_node_binop
403 extends TextSearchQuery_node
404 {
405     function TextSearchQuery_node_binop($leaves) {
406         $this->leaves = $leaves;
407     }
408
409     function _flatten() {
410         // This flattens e.g. (AND (AND a b) (OR c d) e)
411         //        to (AND a b e (OR c d))
412         $flat = array();
413         foreach ($this->leaves as $leaf) {
414             $leaf = $leaf->optimize();
415             if ($this->op == $leaf->op)
416                 $flat = array_merge($flat, $leaf->leaves);
417             else
418                 $flat[] = $leaf;
419         }
420         $this->leaves = $flat;
421     }
422
423     function optimize() {
424         $this->_flatten();
425         assert(!empty($this->leaves));
426         if (count($this->leaves) == 1)
427             return $this->leaves[0]; // (AND x) -> x
428         return $this;
429     }
430
431     function highlight_words($negated = false) {
432         $words = array();
433         foreach ($this->leaves as $leaf)
434             array_splice($words,0,0,
435                          $leaf->highlight_words($negated));
436         return $words;
437     }
438 }
439
440 /**
441  * A (possibly multi-argument) 'AND' conjoin.
442  */
443 class TextSearchQuery_node_and
444 extends TextSearchQuery_node_binop
445 {
446     var $op = "AND";
447     
448     function optimize() {
449         $this->_flatten();
450
451         // Convert (AND (NOT a) (NOT b) c d) into (AND (NOT (OR a b)) c d).
452         // Since OR's are more efficient for regexp matching:
453         //   (?!.*a)(?!.*b)  vs   (?!.*(?:a|b))
454
455         // Suck out the negated leaves.
456         $nots = array();
457         foreach ($this->leaves as $key => $leaf) {
458             if ($leaf->op == 'NOT') {
459                 $nots[] = $leaf->leaves[0];
460                 unset($this->leaves[$key]);
461             }
462         }
463
464         // Combine the negated leaves into a single negated or.
465         if ($nots) {
466             $node = ( new TextSearchQuery_node_not
467                       (new TextSearchQuery_node_or($nots)) );
468             array_unshift($this->leaves, $node->optimize());
469         }
470         
471         assert(!empty($this->leaves));
472         if (count($this->leaves) == 1)
473             return $this->leaves[0];  // (AND x) -> x
474         return $this;
475     }
476
477     function regexp() {
478         $regexp = '';
479         foreach ($this->leaves as $leaf)
480             $regexp .= $leaf->regexp();
481         return $regexp;
482     }
483 }
484
485 /**
486  * A (possibly multi-argument) 'OR' conjoin.
487  */
488 class TextSearchQuery_node_or
489 extends TextSearchQuery_node_binop
490 {
491     var $op = "OR";
492
493     function regexp() {
494         // We will combine any of our direct descendents which are WORDs
495         // into a single (?=.*(?:word1|word2|...)) regexp.
496         
497         $regexps = array();
498         $words = array();
499
500         foreach ($this->leaves as $leaf) {
501             if ($leaf->op == 'WORD')
502                 $words[] = preg_quote($leaf->word, '/');
503             else
504                 $regexps[] = $leaf->regexp();
505         }
506
507         if ($words)
508             array_unshift($regexps,
509                           '(?=.*' . $this->_join($words) . ')');
510
511         return $this->_join($regexps);
512     }
513
514     function _join($regexps) {
515         assert(count($regexps) > 0);
516
517         if (count($regexps) > 1)
518             return '(?:' . join('|', $regexps) . ')';
519         else
520             return $regexps[0];
521     }
522 }
523
524
525 ////////////////////////////////////////////////////////////////
526 //
527 // Parser:
528 //   op's (and, or, not) are forced to lowercase in the tokenizer.
529 //
530 ////////////////////////////////////////////////////////////////
531 define ('TSQ_TOK_BINOP',  1);
532 define ('TSQ_TOK_NOT',    2);
533 define ('TSQ_TOK_LPAREN', 4);
534 define ('TSQ_TOK_RPAREN', 8);
535 define ('TSQ_TOK_WORD',   16);
536 define ('TSQ_TOK_STARTS_WITH', 32);
537 define ('TSQ_TOK_ENDS_WITH', 64);
538 define ('TSQ_TOK_EXACT', 128);
539 define ('TSQ_TOK_REGEX', 256);
540 define ('TSQ_TOK_REGEX_GLOB', 512);
541 define ('TSQ_TOK_REGEX_PCRE', 1024);
542 define ('TSQ_TOK_REGEX_SQL', 2048);
543 // all bits from word to the last.
544 define ('TSQ_ALLWORDS', (2048*2)-1 - (16-1));
545
546 class TextSearchQuery_Parser 
547 {
548     /*
549      * This is a simple recursive descent parser, based on the following grammar:
550      *
551      * toplist  :
552      *          | toplist expr
553      *          ;
554      *
555      *
556      * list     : expr
557      *          | list expr
558      *          ;
559      *
560      * expr     : atom
561      *          | expr BINOP atom
562      *          ;
563      *
564      * atom     : '(' list ')'
565      *          | NOT atom
566      *          | WORD
567      *          ;
568      *
569      * The terminal tokens are:
570      *
571      *
572      * and|or             BINOP
573      * -|not              NOT
574      * (                  LPAREN
575      * )                  RPAREN
576      * /[^-()\s][^()\s]*  WORD
577      * /"[^"]*"/          WORD
578      * /'[^']*'/          WORD
579      *
580      * ^WORD              STARTS_WITH
581      * WORD*              STARTS_WITH
582      * *WORD              ENDS_WITH
583      * ^WORD$             EXACT
584      */
585
586     function parse ($search_expr, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
587         $this->lexer = new TextSearchQuery_Lexer($search_expr, $case_exact, $regex);
588         $this->_regex = $regex;
589         $tree = $this->get_list('toplevel');
590         assert($this->lexer->eof());
591         unset($this->lexer);
592         return $tree;
593     }
594     
595     function get_list ($is_toplevel = false) {
596         $list = array();
597
598         // token types we'll accept as words (and thus expr's) for the
599         // purpose of error recovery:
600         $accept_as_words = TSQ_TOK_NOT | TSQ_TOK_BINOP;
601         if ($is_toplevel)
602             $accept_as_words |= TSQ_TOK_LPAREN | TSQ_TOK_RPAREN;
603         
604         while ( ($expr = $this->get_expr())
605                 || ($expr = $this->get_word($accept_as_words)) ) {
606             $list[] = $expr;
607         }
608
609         if (!$list) {
610             if ($is_toplevel)
611                 return new TextSearchQuery_node;
612             else
613                 return false;
614         }
615         return new TextSearchQuery_node_and($list);
616     }
617
618     function get_expr () {
619         if ( !($expr = $this->get_atom()) )
620             return false;
621         
622         $savedpos = $this->lexer->tell();
623         while ( ($op = $this->lexer->get(TSQ_TOK_BINOP)) ) {
624             if ( ! ($right = $this->get_atom()) ) {
625                 break;
626             }
627             
628             if ($op == 'and')
629                 $expr = new TextSearchQuery_node_and(array($expr, $right));
630             else {
631                 assert($op == 'or');
632                 $expr = new TextSearchQuery_node_or(array($expr, $right));
633             }
634
635             $savedpos = $this->lexer->tell();
636         }
637         $this->lexer->seek($savedpos);
638
639         return $expr;
640     }
641     
642
643     function get_atom() {
644         if ($word = $this->get_word(TSQ_ALLWORDS))
645             return $word;
646
647         $savedpos = $this->lexer->tell();
648         if ( $this->lexer->get(TSQ_TOK_LPAREN) ) {
649             if ( ($list = $this->get_list()) && $this->lexer->get(TSQ_TOK_RPAREN) )
650                 return $list;
651         }
652         elseif ( $this->lexer->get(TSQ_TOK_NOT) ) {
653             if ( ($atom = $this->get_atom()) )
654                 return new TextSearchQuery_node_not($atom);
655         }
656         $this->lexer->seek($savedpos);
657         return false;
658     }
659
660     function get_word($accept = TSQ_ALLWORDS) {
661         foreach (array("WORD","STARTS_WITH","ENDS_WITH","EXACT",
662                        "REGEX","REGEX_GLOB","REGEX_PCRE") as $tok) {
663             $const = constant("TSQ_TOK_".$tok);
664             if ( $accept & $const and ($word = $this->lexer->get($const)) ) {
665                 $classname = "TextSearchQuery_node_".strtolower($tok);
666                 return new $classname($word);
667             }
668         }
669         return false;
670     }
671 }
672
673 class TextSearchQuery_Lexer {
674     function TextSearchQuery_Lexer ($query_str, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
675         $this->tokens = $this->tokenize($query_str, $case_exact, $regex);
676         $this->pos = 0;
677     }
678
679     function tell() {
680         return $this->pos;
681     }
682
683     function seek($pos) {
684         $this->pos = $pos;
685     }
686
687     function eof() {
688         return $this->pos == count($this->tokens);
689     }
690     
691     /**
692      * TODO: support more regex styles, esp. prefer the forced ones over auto
693      * re: and // stuff
694      */
695     function tokenize($string, $case_exact=false, $regex=TSQ_REGEX_AUTO) {
696         $tokens = array();
697         $buf = $case_exact ? ltrim($string) : strtolower(ltrim($string));
698         while (!empty($buf)) {
699             if (preg_match('/^(and|or)\b\s*/i', $buf, $m)) {
700                 $val = strtolower($m[1]);
701                 $type = TSQ_TOK_BINOP;
702             }
703             elseif (preg_match('/^(-|not\b)\s*/i', $buf, $m)) {
704                 $val = strtolower($m[1]);
705                 $type = TSQ_TOK_NOT;
706             }
707             elseif (preg_match('/^([()])\s*/', $buf, $m)) {
708                 $val = $m[1];
709                 $type = $m[1] == '(' ? TSQ_TOK_LPAREN : TSQ_TOK_RPAREN;
710             }
711             // ^word
712             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
713                     and preg_match('/^\^([^-()][^()\s]*)\s*/', $buf, $m)) {
714                 $val = $m[1];
715                 $type = TSQ_TOK_STARTS_WITH;
716             }
717             // word*
718             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
719                     and preg_match('/^([^-()][^()\s]*)\*\s*/', $buf, $m)) {
720                 $val = $m[1];
721                 $type = TSQ_TOK_STARTS_WITH;
722             }
723             // *word
724             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
725                     and preg_match('/^\*([^-()][^()\s]*)\s*/', $buf, $m)) {
726                 $val = $m[1];
727                 $type = TSQ_TOK_ENDS_WITH;
728             }
729             // ^word$
730             elseif ($regex & (TSQ_REGEX_AUTO|TSQ_REGEX_POSIX|TSQ_REGEX_PCRE)
731                     and preg_match('/^\^([^-()][^()\s]*)\$\s*/', $buf, $m)) {
732                 $val = $m[1];
733                 $type = TSQ_TOK_EXACT;
734             }
735             // "words "
736             elseif (preg_match('/^ " ( (?: [^"]+ | "" )* ) " \s*/x', $buf, $m)) {
737                 $val = str_replace('""', '"', $m[1]);
738                 $type = TSQ_TOK_WORD;
739             }
740             // 'words '
741             elseif (preg_match("/^ ' ( (?:[^']+|'')* ) ' \s*/x", $buf, $m)) {
742                 $val = str_replace("''", "'", $m[1]);
743                 $type = TSQ_TOK_WORD;
744             }
745             // word
746             elseif (preg_match('/^([^-()][^()\s]*)\s*/', $buf, $m)) {
747                 $val = $m[1];
748                 $type = TSQ_TOK_WORD;
749             }
750             else {
751                 assert(empty($buf));
752                 break;
753             }
754             $buf = substr($buf, strlen($m[0]));
755
756             /* refine the simple parsing from above: bla*bla, bla?bla, ...
757             if ($regex and $type == TSQ_TOK_WORD) {
758                 if (substr($val,0,1) == "^")
759                     $type = TSQ_TOK_STARTS_WITH;
760                 elseif (substr($val,0,1) == "*")
761                     $type = TSQ_TOK_ENDS_WITH;
762                 elseif (substr($val,-1,1) == "*")
763                     $type = TSQ_TOK_STARTS_WITH;
764             }
765             */
766             $tokens[] = array($type, $val);
767         }
768         return $tokens;
769     }
770     
771     function get($accept) {
772         if ($this->pos >= count($this->tokens))
773             return false;
774         
775         list ($type, $val) = $this->tokens[$this->pos];
776         if (($type & $accept) == 0)
777             return false;
778         
779         $this->pos++;
780         return $val;
781     }
782 }
783
784 // Local Variables:
785 // mode: php
786 // tab-width: 8
787 // c-basic-offset: 4
788 // c-hanging-comment-ender-p: nil
789 // indent-tabs-mode: nil
790 // End:   
791 ?>