Skip to content

Instantly share code, notes, and snippets.

@timstermatic
Last active December 15, 2015 08:09
Show Gist options
  • Save timstermatic/5228829 to your computer and use it in GitHub Desktop.
Save timstermatic/5228829 to your computer and use it in GitHub Desktop.
Finds an extract from a string (n) words before a matched word and highlights any occurrences
/**
* $str to search
* $query word to search for
* $words either side of first match to return
*/
function highlightedExtract($str, $query, $words) {
$pos = stripos($str,$query);
$after = substr($str,$pos,$words);
$prior = explode($after,$str);
$prior = '...' . substr($prior[0],-$words);
return preg_replace("/".preg_quote($query, "/")."/i", "<span class='highlight'>$0</span>", $prior.$after).' ...';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment