tags:

views:

87

answers:

2

I'm working on a site that pulls various public RSS feeds down. I want to show a HTMLless, short description of the feed entry.

Some of the feeds come with a nice excerpt but lots don't so I'm left making my own from the full-content.

So what is the best/quickest/easiest way to take a block of text and slice it down to just the first couple of lines?

+2  A: 

This function will reduce a block of text to a given word limit, so it wont cut if off part way through a word:

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

Example usage:

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

Outputs:

Hello here is a long ...
karim79
Nice trick with the second argument of str_word_count. +1
Ionuț G. Stan
+1  A: 

This one will give you a little more flexibility

function string_limiter($string, $limit = 50, $end_char = '…')
{
 if (trim($string) == '')
 {
  return $string;
 }

 preg_match('/^\s*+(?:\S++\s*+){1,'.(int) $limit.'}/', $string, $matches);

 if (strlen($string) == strlen($matches[0]))
 {
  $end_char = '';
 }

 return rtrim($matches[0]).$end_char;
}

Example how to call it

$str = "Cras id ipsum accumsan dolor pulvinar sollicitudin et eu augue. Pellentesque sem metus, imperdiet tempor fringilla quis, convallis quis nisl. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Etiam eget lorem ligula. Sed congue odio enim. Etiam aliquet condimentum pellentesque. Sed urna velit, egestas et dictum non, pulvinar quis dui! Cras blandit porttitor tortor nec eleifend. Nullam porttitor scelerisque nunc, id porttitor orci lobortis nec. Curabitur vestibulum molestie purus, eget convallis dolor luctus eu! Morbi id felis eu eros mattis congue non nec nisl.";

echo string_limiter($str, 20);

You will get something like this:

Cras id ipsum accumsan dolor pulvinar sollicitudin et eu augue. Pellentesque sem metus, imperdiet tempor fringilla quis, convallis quis nisl.…

Iman Samizadeh