Last active
December 15, 2015 08:09
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* $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