Help function for truncating text strings.

Objective

Create one function that controls the length for one string of characters in drupal.

Function

/*
 * Help function for truncating text strings.
 *
 * @param $string
 *   The string to truncate.
 * @param $length
 *   The lenght for truncate.
 * @param $replacement
 *   The replacement at the end of the string.
 * @return
 *   The truncated string.
 */
function max_length($string, $length = 50, $replacement = '...') {
  if (!is_string($string)) {
    return '';
  }
 
  $string = check_plain($string);
 
  if (drupal_strlen($string) > $length) {
    $output = substr($string, 0, $length) . $replacement;
  }
  else {
    $output = $string;
  }
 
  return $output;
}

 

Powered by Drupal. Created with ZenWalk.