Home > PHP, Snippets of Code > Getting snippets as search results in PHP

Getting snippets as search results in PHP

The following PHP code is a function that extracts snippets of text from a corpus, matching a given keyword and highlighting it with an HTML bold tag:

function get_snippet($keyword, $txt) {
  $snippet='';
  $span = 15;
  preg_match_all("#(\W.{0,$span}\W)($keyword)(\W.{0,$span}\W)#i", "  $txt  ", $matches);
  foreach($matches[0] as $match) {
    if (!$match = trim($match)) continue;
    if (isset($snippet)) $snippet .= "$match..."; else $snippet = "...$match...";
  }
  $snippet = preg_replace("#($keyword)#i", '<b>$1</b>', $snippet);
  return $snippet;
}

Applying to a text like this:

Since its launch in November 2007, Android has not only dramatically increased consumer choice but also
improved the entire mobile experience for users. Today, more than 150 million Android devices have been
activated worldwide with over 550,000 devices now lit up every day through a network of about 39 manufacturers
and 231 carriers in 123 countries. Given Android’s phenomenal success, we are always looking for new ways to
supercharge the Android ecosystem. That is why I am so excited today to announce that we have agreed to acquire
Motorola.

Would throw an output like this, when searching for “Android” keyword:

...November 2007, Android has not only...150 million Android devices have....
Given Android’s phenomenal...supercharge the Android ecosystem. That...
Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: