note 57166 deleted from function.str-word-count by danbrown
| From: | danbrown@php.net | Date: | Fri, 31 Aug 2012 16:28:06 +0000 |
| Subject: | note 57166 deleted from function.str-word-count by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-190373@lists.php.net to get a copy of this message | ||
Note Submitter: webmaster at joshstmarie dot com
----
Trying to make an effiecient word splitter, and "paragraph limiter", eg, limit item text
to 100, or 200 words and so-forth.
I don't know how well this compares, but it works nicely.
function trim_text($string, $word_count=100)
{
$trimmed = "";
$string = preg_replace("/\040+/"," ", trim($string));
$stringc = explode(" ",$string);
echo sizeof($stringc);
if($word_count >= sizeof($stringc))
{
// nothing to do, our string is smaller than the limit.
return $string;
}
elseif($word_count < sizeof($stringc))
{
// trim the string to the word count
for($i=0;$i<$word_count;$i++)
{
$trimmed .= $stringc[$i]." ";
}
if(substr($trimmed, strlen(trim($trimmed))-1, 1) == '.')
return trim($trimmed).'..';
else
return trim($trimmed).'...';
}
}
$text = "some test text goes in here, I'm not sure, but ok.";
echo trim_text($text,5);