Trimming Text Safely in Drupal

Something more for the developer blog ;)

There are two options that work pretty well for trimming text in D7 with a higher degree of safety than trying to knock it out with php alone.

1) When you want no html in your trimmed text

<?php
$myTrimmedText
= strip_tags($sSomeText);

//truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1)

$myTrimmedText = truncate_utf8($sSomeText, 100, TRUE, TRUE);
?>

The 100 is the max length (including ellipsis), the first Boolean is the directive to break it on a word boundary, the second Boolean controls addition of ellipsis, and the last integer (optional) specifies the minimum length of what is considered a word.

http://api.drupal.org/api/drupal/includes--unicode.inc/function/truncate...

2) When you want to preserve the html that might be present in $someText
, this next method is from a function that is part of Views (so it is contrib and the only documentation I have found is here http://api.lullabot.com/views_trim_text/7

<?php
views_trim_text
($aAlter, $sSomeText);
?>

$aAlter is an array of options.
· max_length: Maximum lenght of the string, the rest gets truncated.
· word_boundary: Trim only on a word boundary.
· ellipsis: Trim only on a word boundary.
· html: Make sure that the html is correct.

After much looking to see what the parameters actually need to be set for, I looked in the function and see that values of the options can be anything at all. The function only looks to see that they are not empty. So putting anything in it, turns the option on.

Example in use:

<?php
  $aAlter
= array(
   
'max_length' => 500,
   
'word_boundary' => 'yes', // can be anything.  'no' will have the same effect as 'yes', if you want it to break at the exact char count, leave this out.
   
'ellipsis' => 'yes',   // can be anything.  'no' will have the same effect as 'yes', if you want no ellipses, leave this out.
   
'html' => 'yes'  // can be anything.  'no' will have the same effect as 'yes', if you want no correction of html, leave this out.
);

 $sOutput = views_trim_text($aAlter, $sSomeText);
?>

section: