views:

52

answers:

3

In mysql boolean match, if no operators are present, OR is implied. If you want AND, you need to add + to each keywords.

So query "word1 word2" is equal to "word1 OR word2", "+word1 +word2" is equal to "word1 AND word2"

I don't want users to have to enter + before each keyword, what are my options?

Suggested option 1: Is there something in my.conf I can change to set the defaults (I didn't find anything)

Suggested option 2: parse the query and manually add + to each word. Any simple code for this you can share?

The problem with this is if the user adds "quotes" or operators (+-*<>) etc. it breaks my parsing code.

A: 

Not sure what you mean, but here is an example of how you can add + in front of each word.

$s = "a string with several words in it";
$words = preg_split('/\s+/',$s,null,PREG_SPLIT_NO_EMPTY);
if (count($words)) {
    $str = '+' . implode(' +',$words);
}
Peter Lindqvist
+3  A: 

I went with second suggestions on my site.

Simple one liner to add + before each word if you deal only with words, (not with quoted strings)

$q = implode(' ', array_map(create_function('$a', 'return "+".$a;'), preg_split('`\\s+`', $q))))

or even simpler regex replace doing the same:

echo preg_replace('`(\\W|^)\\w`', '\\1+\\2', $q);

if you have not only single words but also quoted phrases to search this should add + before each single unquoted word and each quoted string

echo preg_replace('`(\\s|^)(\\w|"[^"]+")`', '\\1+\\2', $q);
Kamil Szot
+1 for the one liner implode call!
Peter Lindqvist
thanks, but that was first thing that came to my mind and is a bit of overkill, second form with only one preg_replace call is much better
Kamil Szot
I agree, but i kinda like the concept of the first one better.
Peter Lindqvist
The second regexp also works when a word is already prefixed with a '+'. For the first, the `(\\W|^)` can be replaced by a `\b`, unless the string contains non-ASCII letters (as Ned notes: http://us2.php.net/manual/en/reference.pcre.pattern.syntax.php#54830). OP probably knows this, but escaping a backslash in a single-quoted string is unnecessary unless it's before a single quote or there's a sequence of backslashes, though doing so isn't bad.
outis
Kamil...your 3rd suggestion worked like a charm...Happy Turkey Day!
A: 

There is no way of changing the behavior of full-text matching in boolean mode with no operators, short of editing the source. You'll have to use option 2 (as the others show) in some form or another. Just be careful how you do it, if the search expression comes from the user.

outis