Caution: old code. It's been over 8 months since I wrote this -- and looking back, I can see a couple of bad ideas. But hey, it worked for me, and PPT used(uses) this.
This function generates the WHERE clause of a mysql-query, based on search terms, and search fields provided. The idea is quite simple.
Suppose you wanted to index every single page of your website by an internal search engine. Place the
tagless contents of your content-files into a mysql table (suppose page_name, page_content as columns); create a PHP script (form) to get the search terms from the user, and then simply SELECT page_name FROM {your_index_table} WHERE {buildSearchQuery($user_inputed_terms,'page_content');}. This would give you the names of the pages that matched the query.
The script supports "search phrases" (quote two or more words to search for them appearing next to each other), NOT search terms (place a minus before the term), excluding common words, forcing inclusion of words (place a plus before the word).
In other words: fairly simple code.
Code:
<?php
function buildSearchQuery($terms, $fields) {
$disallow = implode('|',explode(',','the,he,she,his,hers,it,will,has,been,where,how,when,if,had,can,may,could,not,and,why,because,no,am,is,was'));
$terms = trim($terms);
$sC = 0; //search element count
while ($terms != '') {
if (substr($terms,0,1) == '"' and substr_count($terms,'"') > 1) {
$end = strpos($terms,'"',1);
$element = substr($terms,0,$end);
$terms = substr(strstr(substr($terms,1),'"'),1);
} else {
$end = strpos($terms,' ');
if ($end === FALSE) $end = strlen($terms);
$element = substr($terms,0,$end);
if ($end == strlen($terms)) { $terms = ''; } else { $terms = substr($terms, $end); }
}
$element = trim(ereg_replace('(\?|!|\.)','',$element));
$terms = trim($terms);
if (strlen($element) == 1) {
$stat['filter'] .= ', '.$element;
} elseif (substr($element,0,1) == '-' or
substr($element,0,1) == '+' or
substr($element,0,1) == '"') {
$seat[$sC] = str_replace('"','',$element);
$sC += 1;
} else {
$insert = trim(ereg_replace(' ('.$disallow.') ','',' '.$element.' '));
if (trim($insert) != '') {
$seat[$sC] = $insert;
$sC += 1;
}
}
}
for ($i=0;$i < $sC;$i++) {
$not = '';
$el = $seat[$i];
$sChar = substr($el,0,1);
if ($sChar == '-') {
$not = 'NOT ';
$el = substr($el,1);
} elseif ($sChar == '+') {
$el = substr($el,1);
}
$el = mysql_escape_string($el);
$where .= " and ${not}(";
foreach ($fields as $field) {
$where .= ' '.$field." LIKE '%$el%' or";
}
$where = trim(substr($where,0,strlen($where)-2));
$where .= ')';
}
$where = trim(substr($where,4));
return $where;
}
?>