Last active
December 23, 2017 23:38
-
-
Save niketpathak/6ed0a78edd3a8ed9a46c7b53e17eee21 to your computer and use it in GitHub Desktop.
Generate an Excerpt from given content. Strips off html tags and preserves word boundaries
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
<?php | |
echo generateExcerpt('Some long text is not really present here', 15); // Some long... | |
/** | |
* Generate an Excerpt for a given String | |
* @param string $content The content | |
* @param int $maxLength The maximum length of the desired excerpt | |
* @param string $more the string to use as more | |
* @return string | |
*/ | |
function generateExcerpt($content = null, $maxLength = 300, $more = '...') { | |
if (empty($content)) return ''; | |
$excerpt = strip_tags(trim(preg_replace('/\s+/', ' ', $content))); | |
$maxLength = $maxLength - strlen($more); | |
if (strlen($excerpt) > $maxLength) { | |
$excerpt = substr($excerpt, 0, $maxLength); // strip the text to the desired length | |
$excerpt = substr($excerpt, 0, strrpos($excerpt, " ")); // get last space character to preserve word boundaries | |
$excerpt = $excerpt . $more; // concatenate 'more' text | |
} | |
return $excerpt; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment