You're here: Home / PHP /

Get Summary From a Long Paragraph

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.

<?php
function get_summary($text, $wordnum = 20)
{
    /* count multiple spaces as one space */
    $text  = preg_replace("/ +/", " ", $text);
    $pos   = 0;
    $count = 0;
    
    while(($pos = strpos($text, ' ', $pos+1)) !== false) {
        if (++$count >= $wordnum) {
            break;
        }
    }
    
    $summary = substr($text, 0, $pos);
    return($summary);
}

$text = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec "
      . "libero. Suspendisse bibendum. Cras id urna. Morbi tincidunt, orci "
      . "ac convallis aliquam, lectus turpis varius lorem, eu posuere nunc "
      . "justo tempus leo.";

$sum = get_summary($text);
print $sum;

/* will print:
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec libero.
Suspendisse bibendum. Cras id urna. Morbi tincidunt, orci ac convallis
*/

Keywords: text manipulation, get summary, string functions, php

Share:  del.icio.us logo Save to del.icio.us  digg logo Digg this!

comment.gifAdd your comment

(required, will not be published) (optional)