Generate Excerpt without Breaking a Word

Here’s a little snippet for generating an excerpt without breaking up a word:

function excerpt($string='', $maxChar=50, $uri='#') {
     $length = strlen($string);
     if ($length < $maxChar) {
          return $string;
     }
     $trimmedString = substr($string, 0, $maxChar);
     $choppedString = substr($trimmedString, 0, strrpos($trimmedString, strrchr($trimmedString, ' ')));
     $newString = $choppedString . ' <a href="' . $uri . '">more</a>';
     return $newString;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *