patternphpMinor
Please help and improve this script for displaying search results
Viewed 0 times
thisscriptpleasesearchhelpdisplayingimproveforandresults
Problem
I wrote a search script, now I want a more efficient way of finding the keywords used for the search and make them bold. I used this code but it I feel it could be greatly improved on. Thanks for any suggestion.
I use this code to make the keywords bold
// I use this code to select the lines to display
$lines = explode('.', trim($search_result));
// Break up the result into sentences
$j = 0; $line = '';
for($i = 0; $i < sizeof($lines); $i++) {
// Look for the keywords in each of the line
if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) ||
strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3])
) {
$j++;
$line .= trim($lines[$i])."...";
}
if ($j == 2)
return $line;
// If no keyword is found in first 100 lines/sentences, just display the first 3 lines
if ($i == 100)
return $lines[0]."...".$lines[1]."...".$lines[2];
}I use this code to make the keywords bold
function findAndReplace($keywords, $sentence) {
for ($i=0; $i".ucfirst($keywords[$i])."";
return str_ireplace($keywords, $words, $sentence);
}Solution
A couple of small things...
I would replace this:
with something like:
Also, this line:
will result in an extra trailing "..." when $j gets to 2. I'm presuming you want something like "line1...lineN", but instead you'll get "line1...lineN...". You probably want to chop off those extra dots, or only add them when needed.
I would replace this:
if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) ||
strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3])with something like:
foreach($keyword in $keywords) {
if (strstr($lines[$i]) {
$j++;
$line .= trim($lines[$i])."...";
break;
}
}Also, this line:
$line .= trim($lines[$i])."...";will result in an extra trailing "..." when $j gets to 2. I'm presuming you want something like "line1...lineN", but instead you'll get "line1...lineN...". You probably want to chop off those extra dots, or only add them when needed.
Code Snippets
if (strstr($lines[$i], $keywords[0]) || strstr($lines[$i], $keywords[1]) ||
strstr($lines[$i], $keywords[2]) || strstr($lines[$i], $keywords[3])foreach($keyword in $keywords) {
if (strstr($lines[$i]) {
$j++;
$line .= trim($lines[$i])."...";
break;
}
}$line .= trim($lines[$i])."...";Context
StackExchange Code Review Q#4725, answer score: 2
Revisions (0)
No revisions yet.