PDA

View Full Version : help with REGEXP, please


maltrecho
06-24-2003, 11:41 AM
In MySQL,when using REGEXP in a query, if I write 'word1|word2', the results will match all the rows containing ('word1' or 'word2'). What is the simplest way to match rows containing ('word1' and 'word2')?.

Example1:(...input type="... value="word1 or word2"... SUBMIT!)

Example2:(...input type="... value="word1 and word2"... SUBMIT!)

$keywords = stripslashes(trim($_GET['keywords']);

$keywords = str_replace(" or ", "|", $keywords); /* this one works great */

$keywords = str_replace(" and ", "???", $keywords); /* How to manage this one ??? */

$query = "SELECT name,
description
FROM table
WHERE ( (name REGEXP '$keywords')
OR (description REGEXP '$keywords') )";

The first one searches for 'word1' or 'word2' in all rows.
The second one should search for 'word'1 and 'word2' in the same row.

THANKS IN ADVANCED.

maltrecho
06-24-2003, 11:48 AM
Sorry I didn't mean the emoticons...

maltrecho
06-25-2003, 08:07 PM
In MySQL,when using REGEXP in a query, if I write 'word1|word2', the results will match all the rows containing ('word1' or 'word2').
What is the simplest way to match rows containing ('word1' and 'word2')?.


----------FORM PAGE:------------

...method="get"...

Example1:(...input type="text" name="keywords" value="word1 or word2"... SUBMIT!)

Example2:(...input type="text" name="keywords" value="word1 and word2"... SUBMIT!)

----------SEARCH PAGE:----------

$keywords = stripslashes(trim($_GET['keywords']);

$keywords = str_replace(" or ", "|", $keywords); /* this one works but not perfectly (see below) */

$keywords = str_replace(" and ", "???", $keywords); /* How to manage this one ? */

$query = "SELECT name,
description
FROM table
WHERE ( (name REGEXP '$keywords')
OR (description REGEXP '$keywords') )";

--------------------------------

The first example searches for 'word1' or 'word2' in all rows.
The second example should search for 'word'1 and 'word2' in the same row. How could I do that?

Another thing is that if the user inserts (by mistake that is) more than one space between the 'or' and the 'words' (-=space): 'word1--or-word2', the function 'trim' doesn't seem to work combined with the 'str_replace' function, and the 'str_replace' function will return (echo, print) 'word1 or word2' insead of 'word1|word2'. How can I fix that?

THANKS IN ADVANCED.

raf
06-25-2003, 09:27 PM
i would do it like this:
-in the form, have three fields --> textfield 1 form name, dropdown for operator, textfield2 for description
- in the php, dynamicaly build the sql like

$query = "SELECT name, description FROM table WHERE name LIKE " . trim($_GET['name']) . " $_GET['operator']) description LIKE " . trim($_GET['description']);