View Full Version : need help - duplicate search results problem.

11-16-2006, 02:06 AM
I'm working on http://www.americanquotations.org/search.php .

What I'm trying to do is only return sentences from a result that contain the search term, so this is the procedure I'm following:

split returned quotes into sentences >> check if sentence contains search terms >> if so, return the sentence.

This seems fairly easy to do, but I've ran into a few problems, one being that if a user enters more than one search term duplicate sentences are returned. Another problem is that the $intSentences variable is way off it's intended value. here is the code I'm using:

// break into paragraphs
$strQuote = str_replace("\n", "<br><br>", $row['Quote']);
foreach($strSearch as $valuereplaced){
// highlight search terms
$strQuote = str_ireplace(' '.$valuereplaced.' ', ' <span class="highlight">'.$valuereplaced.'</span> ', $strQuote);
$strQuote = str_ireplace($valuereplaced, '<span class="highlight">'.$valuereplaced.'</span>', $strQuote);
//split paragraphs into sentences
$splitQuote = split('[\.|\?|\!]', $strQuote);
foreach($splitQuote as $valuequote){
foreach($strSearch as $valuesearch){
if (strpos($valuequote, $valuesearch)){
$par .= '<p>'.$valuequote.'...</p>';
//number of sentences containing search
$intSentences = sizeof($splitQuote);



Can someone point me in the right direction to solving this? thanks

11-17-2006, 02:08 AM
I couldn;t quite follow the logic of your code (you have variables in there that haven;t been declared, or were declared in some previous code that is not shown), so why not give this code a try. It's untested, but maybe it will give you some ideas for how to do what you want to do:


$search_term = urldecode($_GET['search_term']);
$search_array = explode(" ",$search_term);
$sentence_array2 = array();

/* Your MySQL query goes here */

while ($row = mysql_fetch_assoc($result))
$quote = $row['Quote'];
$sentence_array = $preg_split('/(\.\s*)|(\?\s*)|(!\s*)/',$quote);

foreach ($search_array as $k => $v)
$v = trim($v);
$pattern = '/'.preg_quote($v,'/').'/';

foreach ($sentence_array as $key => $val)
$val = trim($val);
if (preg_match($pattern,$val) == 1)
if (!in_array($val,$sentence_array2))
$sentence_array2[] = $val;



11-18-2006, 12:30 AM
here is the full source if you were interested :


thanks for helping, I'll plug this code in ASAP and tell you how everything goes.