It's a bit difficult to see exactly what you need to get back here as $string would appear to concatenate all the results which could make for a result that is hard to make sense of for the reader. An example would be useful. However some observations:-
1 If the key word appears in some or all of $string the strpos will only return the location of the first occurrence, you would need to run it again using the first location as the offset to get the subsequent locations. 2 Why not process $row['title'],$row['par1'] and $row['body'] separately and then concatenate? 2 Why not use $arrSearch = explode($trimmed1,$row['title']) etc. If count($arrSearch) > 2 then you know that $trimmed1 appears more than once and if you wished you could use count($arrSearch) to show the searcher how many times it appears in that text. You could then take element 0 check the length and either display the last 50 or all of it, if smaller. Then use substr($keyword1,$row['title'],strpos($string, $trimmed1),50) to display the rest of the string up to 50 characters. 3 It's a small point but you could cut a line from the code by:- $trimmed1 = trim($_POST['keyword1']); Charlie -----Original Message----- From: [email protected] [mailto:[EMAIL PROTECTED] On Behalf Of Tedit kap Sent: 16 May 2008 14:39 To: [email protected] Subject: [php_mysql] charecters before & after keyword in search results i can not do the trick of displaying -+50 characters before and after search keyword in the search results...also it does not give accurate positions of the words I search (just for me to see). what's wrong below? $keyword1=$_POST['keyword1']; //i get keyword from a search form $trimmed1 = trim($keyword1); $query=mysql_query("SELECT * FROM newsa WHERE title LIKE '%$trimmed1%' OR par1 LIKE '%$trimmed1%' OR body LIKE '%$trimmed1%' ORDER BY date DESC LIMIT 100"); while ($row = mysql_fetch_array($query)) { $string=$row['title'].$row['par1'].$row['body']; //in order to search the keyword in title + first paragraph + the rest of the article, first I combine the whole article into one string... am I doing right? $pos = strpos($string, $trimmed1); //i can not get the corrcet position...plus if there is more than one keyword in string, which one is supposed to be returned? echo "$pos"."<br/>"; //this is just to see the position number for my info $pos = $pos - 50; $end = $pos + 50; //actually this is of no use am I wrong? because in substr the last item is the length of string to be displayed, not the end point...so i wrote 100 below... $output = substr($string, $pos, 100); echo "$output";
