I am making a search engine and I would have the user to type a sentence to search for. Let's say
it is stored in $search. My search engine will bring up a result If and only if ALL of the words
in $search exist in the result. For example if
Now, I don't know how many words there are in $search initially. How do I do a search like that?
I mean if I know $search is 3 words then I can do
<?
$words = preg_split("/ /", $search);
if (eregi(".*words[0].*words[1].*words[2].*", 'possible result')) {
.....
}
?>
Even if I know how many words there are, every time the number of words in $search can be different.
another note is that my data is taken from a database.
The Solution:
If you have used explode() you can do a loop that goes through the array, for instance
<?
$searchwords=explode(' ', $search);
for ($x=0;$x<count($searchwords);$x++){
//build the search command OR build the query
// i recommend to make it a query, so:
$WHERE.= ' AND textfield=LIKE '"%'.$searchwords[$x].'%"';
}
//now cut off the first ' AND '
$WHERE=substr($WHERE,4,strlen($WHERE));
//now finish the query
$query="SELECT title,text,ID FROM tablename ".$WHERE;
?>
then proceed by doing the query and showing the results.
Jasp Jones wrote :908
not sure of the php internals but would it be better to get the count before the for loop to save re-evaluating the count on each loop? also a nice way to get around chopping the first `AND` off is to put `WHERE 1 = 1` || $ANDS
cheers
Jasp
Roberto Schiabel wrote :917
what if your search must apply more than one field.
do you use a nested-cicle to build a sql statement to mach all the words in every field ?