Skip to content

Instantly share code, notes, and snippets.

@amgraham
Last active September 23, 2015 21:57
Show Gist options
  • Save amgraham/621679 to your computer and use it in GitHub Desktop.
Save amgraham/621679 to your computer and use it in GitHub Desktop.
Displays the needle, and some surrounding text, within a haystack
function excerpt($text, $phrase, $radius = 50, $ending = "...", $offset = 0) {
// excerpt('SuperLongStringThatMightNotFitInTheSpaceAllowed', 'That', 10)
// will return
// rLongStringThatMightNotFi...
$phraseLen = strlen($phrase);
if ($radius < $phraseLen) {
$radius = $phraseLen;
}
$pos = strpos(strtolower($text), strtolower($phrase), $offset);
$startPos = 0;
if ($pos > $radius) {
$startPos = $pos - $radius;
}
$textLen = strlen($text);
$endPos = $pos + $phraseLen + $radius;
if ($endPos >= $textLen) {
$endPos = $textLen;
}
$excerpt = substr($text, $startPos, $endPos - $startPos);
if ($startPos != 0) {
$excerpt = substr_replace($excerpt, $ending, 0, $phraseLen);
}
if ($endPos != $textLen) {
$excerpt = substr_replace($excerpt, $ending, -$phraseLen);
}
return $excerpt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment