Re: Truncate words in multiple paragraphs

From: Date: Fri, 03 Feb 2006 22:02:02 +0000
Subject: Re: Truncate words in multiple paragraphs
References: 1 2  Groups: php.general 
Request: Send a blank email to php-general+get-229852@lists.php.net to get a copy of this message
On 3-Feb-06, at 4:19 PM, Richard Lynch wrote:
On Fri, February 3, 2006 10:54 am, Verdon Vaillancourt wrote:
I am using the following function (that I found in the user comments on php.net manual) for trimming the number of words accepted via a form field // Truncation is by word limit, not character limit. So if you limit // to 255, then it will cut off a text item to 255 words, not 255 characters function trim_text ($string, $truncation=250) { $string = preg_split("/\s+/",$string,($truncation+1));
This splits it apart on any whitespace.
unset($string[(sizeof($string)-1)]); return implode(' ',$string);
This re-assembles it with spaces as the only whitespace.
}
There's probably some way to do it with built-in functions, but here's a solution: function trim_text($string, $truncation = 250){ //search for words/whitespace for($w=false,$l=strlen($string),$c=0,$t=0; $t<$truncation && $c<$l;$c++){
    $char = $string[$c];
    //detect change of state from 'word' to 'whitespace':
    if (!$w && strstr(" \t\r\n", $char)){
      $w = true;
    }
    elseif($w && !strstr(" \t\r\n", $char)){
      $w = false;
      $t++;
    }
} return substr($string, 0, $c); } This is NOT going to be fast on large pieces of text, because PHP loop is relatively slow -- So if somebody posts a working function using built-in PHP functions, it will probably be faster. This mostly works too, and in my circumstances, I'm not using it on any large blocks. I also like that it takes tabs into account.
One thing, if I feed it a string of say 300 words in multiple paragraphs, it returns a string of 251 words... 250 intact words and the first letter of the 251st word (at least in the tests I've done so far) regards, verdon
-- Like Music? http://l-i-e.com/artists.htm


« previous php.general (#229852) next »