1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...

print first N sentences

Here’s a cool function i found today while i was working on a project.

it prints the first n sentence.

function getLeadingSentences($data, $max)
{
//given string $data, will return the first $max sentences in that string
//in: $data = the string to parse, $max = maximum # of sentences to return
//returns: string containing the first $max sentences
//(If the # of sentences in the string is less than $max,
//then entire string will be returned.)
//a sentence is any charactors except ., !, and ?
//any number of times,  plus one or more .s, ?s, or !s
//and any leading or trailing whitespace:
$re = "^s*[^.?!]+[.?!]+s*";
$out = "";
for($i = 0; $i < $max; $i++) {
if(ereg($re, $data, $match)) {
//if a sentence is found, take it out of $data and add it to $out
$out .= $match[0];
$data = ereg_replace($re, "", $data);
}
else {
$i = $max;
}
}
return $out;
}
//EXAMPLE:
$start = "Sentence one...  Sentence two?  Sentence three!  Sentence four.";
$end = getLeadingSentences($start, 3);
echo("result: $end"); 

[source]

Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • MySpace
  • Reddit
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter
  • Yahoo! Bookmarks
  • #1
    Posted by I LOVE you Sarah » Blog Archive » Defining love – Part 3 on July 15th, 2009 at 7:32 AM

    [...] print first N sentences | Just a bunch of code [...]

  • #2
    Posted by Jason on July 25th, 2009 at 11:36 AM

    Heh…I wrote that code for a project I did eons ago. Glad you found it useful.

  • #3
    Posted by Sarah on March 1st, 2010 at 10:48 PM

    Amazing how old things get dredged up. Thanks!

    I just added this line before the return

    if (empty($out) && !empty($data)) $out = $data;

Share your opinion! Post your thoughts.