| px | top | add code | search | signup | login | help |
<?
//getLeadingSentences
//Copyright (c) 2000 Jason R. Pitoniak. All rights reserved.
//jason@interbrite.com http://www.interbrite.com
//If you find this code useful, find a bug, or have a suggestion,
//please email me. Feel free to use this code for any purpose.
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");
?>
Comments or questions?
PX is running PHP 5.2.11
Thanks to Miranda Productions for hosting and bandwidth.
Use of any code from PX is at your own risk.