Shorten text

Wednesday, March 17th, 2010

This is a small function that shortens a string.
It looks if the string is longer than a preset length, and if so cuts the text there.
Then it removes the last word from the string (so your string ends neatly at a space), and adds three dots.

  1. // Shorten a text if nessecary
  2. function shortenText($txt='', $len=0){
  3.  
  4.         if(strlen($txt) > $len){
  5.  
  6.                 $txt = substr($txt, 0, $len);
  7.  
  8.                 $t = split("[\n\r\t ]+", $txt);
  9.                 $t = array_slice($t, 0, -1);
  10.                 $txt = join(' ', $t);
  11.  
  12.                 $txt .= '...';
  13.  
  14.         }
  15.  
  16.         return $txt;
  17. }

Display clean php code for copying

// Shorten a text if nessecary
function shortenText($txt='', $len=0){

	if(strlen($txt) > $len){

		$txt = substr($txt, 0, $len);

		$t = split("[\n\r\t ]+", $txt);
		$t = array_slice($t, 0, -1);
		$txt = join(' ', $t);

		$txt .= '...';

	}

	return $txt;
}
click here to close

Help keep these files free,
and support further development!