[SPT/CWIS] code to not ... in middle of word

Kucera, Rich Kucerar at hhmi.org
Thu Jun 1 14:31:38 CDT 2006


Googled for this.  Found some at drupal site and packaged it into a few
functions.  Using it for description fields.

<?php
function blunt_truncate( $text, $size ) {
	return substr($text, 0, $size);
}
function custom_truncate_text($text, $size, $ensure_limit = FALSE) {
  // If short enough, do nothing.
  if (strlen($text) < $size) {
    return $text;
  }
 
  if($ensure_limit) {
    // We have to stay within limits, but don't want to truncate within a
word 
    $max_text = blunt_truncate($text, $size);
   
    // Remove ' ' => 0 from the array, to always truncate at sentence
borders.
    $breakpoints = array(' ' => 0, "\n" => 0, '. ' => 1, '! ' => 1, '? ' =>
1);
    foreach ($breakpoints as $point => $charnum) {
      if ($length = strrpos($max_text, $point)) {
        return substr($text, 0, $length + $charnum);
      }
    }
    // If a space could not be found, be blunt
    return blunt_truncate($text, $size);
  }
 
  $breakpoints = array("\n" => 0, '. ' => 1, '! ' => 1, '? ' => 1);
  foreach ($breakpoints as $point => $charnum) {
    if ($length = strpos($text, $point, $size)) {
      return substr($text, 0, $length + $charnum);
    }
  }

  // If all else fails, we simply truncate the string.
  return blunt_truncate($text, $size);
}
function excerpt_teaser( $paragraph_text, $excerpt_length ) {
	return custom_truncate_text($paragraph_text, $excerpt_length,
TRUE)."...";
}
 
?>

-----------------------------------------
Rich Kucera
Senior Web Applications Developer
Howard Hughes Medical Institute 
4000 Jones Bridge Road 
Chevy Chase, MD 20815 
(301) 215-8714
 



More information about the SPT-CWIS-Users mailing list