Last active
September 23, 2015 21:57
-
-
Save amgraham/621679 to your computer and use it in GitHub Desktop.
Displays the needle, and some surrounding text, within a haystack
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
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