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]



[...] print first N sentences | Just a bunch of code [...]
Heh…I wrote that code for a project I did eons ago. Glad you found it useful.
Amazing how old things get dredged up. Thanks!
I just added this line before the return
if (empty($out) && !empty($data)) $out = $data;