I am adding a search to my custom blog. It is working okay, but I want the results to look a bit different. At the moment I have a function that limits the text to the first 200 characters of the search term content. However, I would like the text to be limited to 100 characters before and 100 characters after the search term. What do I need to look at changeing to achieve this.
My code so far:
<?php
function short_description($text){
$final = "";
$final = (substr($text, 0, 200) . "...");
echo "<p>" . strip_tags($final) . "</p>";
}
$terms = explode(" ", urldecode($_GET['searchterms'])); // use GET method so users can bookmark searches
$query = "SELECT * FROM entries WHERE (subject LIKE '%" . $terms[0] . "%' OR summary LIKE '%" . $terms[0] . "%' OR body LIKE '%" . $terms[0] . "%' OR author LIKE '%" . $terms[0] . "%')"; //searches for matches to first searchterm
for($i=1; $i<count($terms); $i++){
$query = $query . " OR (subject LIKE '%" . $terms[$i] . "%' OR summary LIKE '%" . $terms[$i] . "%' OR body LIKE '%" . $terms[$i] . "%' OR author LIKE '%" . $terms[$i] . "%')"; //searches for matches to subsequent searchterms
}
$searchresult = mysql_query($query); //execute the query
$searchnumrows = mysql_num_rows($searchresult); //count number of lines returned
$limit = 10; //number of results per page
echo "<p>search for ";
foreach($terms as $key){
echo "<u>" . $key . "</u> ";
}
echo " has <strong>" . $searchnumrows . "</strong> results</p>"; //display each term with underline and number of results
if($searchnumrows == 0){ //display if no matches to search
echo "<p>Sorry, no results match your search</p>";
}
else{
$limitsql = $query . "ORDER BY dateposted DESC LIMIT " . $limit . ";";
$limitres = mysql_query($limitsql);
$limitnumrows = mysql_num_rows($limitres);
while($limitrow = mysql_fetch_assoc($limitres)){
echo "<h2 class=\"pSpaceBefore\">" . "<a href='viewentry.php?id=" . $limitrow['id'] . "'>" . $limitrow['subject'] . "</a></h2>";
echo "<p>posted on " . date("F jS Y",strtotime($limitrow['dateposted'])) . " by " . $limitrow['author'] . "</p>";
short_description($limitrow['body']); //use short_description() function to limit the returned results
}
}
?>