tags:

views:

171

answers:

1

Hi, was wondering how to do a search result using PHP + MySQL but not show all the data in the result but only a SUMMARY (lets say limited to 200 characters). And the summary would exactly contain the keyword portion. So -100 characters+keyword+100 characters might be how it would be shown.

Thanks!

+3  A: 

Assuming you are fine with taking the first instance of the keyword to use in your summary, you could break up the results of your query in PHP in a way similar to this:

 $sql = "SELECT data_field FROM your_table WHERE data_field LIKE '%".$keyword."%'";
 $res = mysql_query($sql);
    while($row = mysql_fetch_array($res)) {
     $data = $row['data_field'];      
     $first_pos = strpos($data,$keyword);
     if ($first_pos !== false) {
                  $output = substr($data,max(0,$first_pos - 100),200 + strlen($keyword));
       echo $output;
     }
 }

Obviously you could do whatever suited your needs with $output once you had it.

zombat
Hey Thanks! But I am getting a parse error on your line with $output=substr($data....
Oops, sorry about that. Messed up the brackets on copy/paste. Try now.
zombat
Wow this is so cool. Hey thanks! I got it working!!
No problem. I made another quick edit to it that improves the length calculation for after the keyword. Should be a bit better.
zombat
I used stripos instead for case-insensitive. One thing I did note is that if the keyword appears more than once in a paragraph, then it doesnt get shortened for some reason. It shows entire result.
My screwup.. I didnt copy your code exactly. Works awesome!