Quantcast
Channel: Coding and Programing » string
Viewing all articles
Browse latest Browse all 10

truncate string to first 20 words in PHP

$
0
0

Problem And Question

How can I truncate a string after 20 words in PHP?

Best Solution And Answer

function limit_text($text, $limit) {
      if (str_word_count($text, 0) > $limit) {
          $words = str_word_count($text, 2);
          $pos = array_keys($words);
          $text = substr($text, 0, $pos[$limit]) . '...';
      }
      return $text;
    }

echo limit_text('Hello here is a long sentence blah blah blah blah blah hahahaha haha haaaaaa', 5);

Outputs:

Hello here is a long ...

Viewing all articles
Browse latest Browse all 10

Trending Articles