Get Summary From a Long Paragraph

Nov 7, 2008 | Tags: PHP | del.icio.us del.icio.us | digg Digg

If you have recent news you want to display in your homepage, you might want to display only the summaries--a short paragraph with only 20-25 words. The simplest way to do this is get the first 20-25 words from your articles. At the end of the summary, and a link with some text like 'read more', 'continue reading' or something like that.

Listing 1: listing-1.php

  1. <?php
  2. function get_summary($text, $wordnum = 20)
  3. {
  4.     /* count multiple spaces as one space */
  5.     $text  = preg_replace("/ +/", " ", $text);
  6.     $pos   = 0;
  7.     $count = 0;
  8.    
  9.     while(($pos = strpos($text, ' ', $pos+1)) !== false) {
  10.         if (++$count >= $wordnum) {
  11.             break;
  12.         }
  13.     }
  14.    
  15.     $summary = substr($text, 0, $pos);
  16.     return($summary);
  17. }
  18.  
  19. $text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec "
  20.       . "libero. Suspendisse bibendum. Cras id urna. Morbi tincidunt, orci "
  21.       . "ac convallis aliquam, lectus turpis varius lorem, eu posuere nunc "
  22.       . "justo tempus leo.";
  23.  
  24. $sum = get_summary($text);
  25. print $sum;
  26.  
  27. /* will print:
  28. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero.
  29. Suspendisse bibendum. Cras id urna. Morbi tincidunt, orci ac convallis
  30. */

1 Comment

Amit Cohen on Dec 14, 2008:

Hi You forgot the closing tag ?> Cheers Amit.

Leave a comment

Name (required)
Email (will not be published) (required)
Website

Characters left = 1000