Quick way to plot keywords in a blurb.
I was updating the search feature to an online store that my company has built, which the whole purpose was to make it “more Google like in features”.
One of the features was plotting the keywords in the short description for that page. This makes the search results a little more relevant for people who are searching for a product or a page that’s housed on their store.
Example: So if someone searches for “John” and that keyword doesn’t appear until the end of the content, rather than just showing the blurb without the keyword highlighted, it should be in the middle or beginning of the blurb.
It’s the difference between seeing:
“The car over heated, but we really didn’t care, because it was Sunday and…”
and seeing:
“…when we walked to the car. John also went to the beach…”
So I came up with some quick code to do just this, it’s quick and dirty, but it does the trick.
function plot_blurb($description, $words, $max = 150) {
$last_position = 99999999999999999;
foreach($words as $word) {
$word = preg_quote($word);
$current_position = stripos($description, trim($word));
if( $current_position > 0 ) {
if( $current_position < $last_position ) {
$last_position = $current_position;
$last_length = strlen($word);
}
}
}
if( strlen($description) > $max ) {
$half = round($max / 2, 0);
$start = $last_position - $half;
if( $start <= 0 ) {
$start = 0;
} else {
$blurb = '...';
}
$blurb .= substr($description, $start, $max) . '...';
} else {
$blurb .= $description;
}
return $blurb;
}
$description is the full text for the page, $words is the array of keywords to find, and $max is the maximum amount of characters to show in the blurb.
Also, this is using the PHP 5 command stripos, PHP 4 users will need this function in order to make it work.
function stripos($haystack, $needle, $offset=0) {
return strpos(strtolower($haystack), strtolower($needle), $offset);
}
Hopefully this will help someone out.