0

I use this function to make excerpt of text and link to full content. Now when reach the count of symbols(letters) is cutting the word. I don't want to cut the on first, second or any word. How to check and make excerpt before or after the word? Here is function that I use

function getExcerpt($str, $startPos=0, $maxLength=150) {
    if(strlen($str) > $maxLength) {
        $excerpt   = substr($str, $startPos, $maxLength-3);
        $lastSpace = strrpos($excerpt, ' ');
        $excerpt   = substr($excerpt, 0, $lastSpace);
        $excerpt  .= '...';
    } else {
        $excerpt = $str;
    }

    return $excerpt;
}
Suman Bogati
  • 6,289
  • 1
  • 23
  • 34
Goro
  • 499
  • 1
  • 13
  • 31

1 Answers1

0

You can use something like this

function getExcerpt($text,$length = 120,$direction = "down") {
    while ( !in_array(mb_substr($text,$length,1,'UTF-8'),array(' ')) ) {
           $direction == "down" ? $length-- : $length++;

           }
        return mb_substr($text,0,$length,'UTF-8');
    }
Jason Paddle
  • 1,095
  • 1
  • 19
  • 37