Re: Truncate words in multiple paragraphs

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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.

-- 
Like Music?
http://l-i-e.com/artists.htm

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux