Truncating text in Drupal

As a themer, you frequently want to cut a bit of text to a certain length, be it for layout reasons, or teasers.

Luckily, instead of trying to figure out how to do it cleanly with PHP, Drupal API provides a very handy function that does what we need to do, to any text string.

truncate_utf8() api.drupal.org/api/function/truncate_utf8/5

Say you want to cut the title of your node to a certain character length in your node.tpl.php template file.  Go into your file and find the $title variable that prints the node title.  Simply wrap it in the function linked above, with whatever extra arguments you want to use.  For example:

<?php print truncate_utf8($title,'10',TRUE,TRUE); ?>

This cuts the node title to 20 characters, and uses wordsafe, so that it only cuts after a word.  The last TRUE argument puts an ellipsis at the end of the text (dot dot dot).