This little tidbit was shared by "As If" in this post http://drupal.org/node/112491 - i thought i'd repost it as a simple function, not so much because it's hard to write, as so much hard to find for people like me who don't know much php, and forget all the syntaxes.

Stick in your template.php

function phptemplate_truncate_text($text_chunk,$size) {
$chunk = substr($text_chunk,0,$size);
$lastspace = strrpos($chunk," ");
$chopped = substr($chunk,0,$lastspace) . "...";
print $chopped;
}

use to chop off any text, for example using a CCK field, where the first variable is whatever text, and the 2nd variable 100 in this case is the number of characters before it gets chopped off.

<?php 
    phptemplate_truncate_text($node->field_my_text_field,100); 
?>

Hope it's useful for someone.

Comments

spooky69’s picture

Verrrrry useful - thanks for that!

Rob T’s picture

Thanks for this post.

The issue I had with the code above is that I couldn't figure out how to make the call a conditional. Using that code above, my body field was forced to be 100, even though the actual content was less or none. So I just modified the code provided in the much-appreciated link: http://drupal.org/node/112491

<?php
if(strlen($body) > 100) {
  $chunk = substr($body,0,100);
  $lastspace = strrpos($chunk," ");
  $body = substr($chunk,0,$lastspace) . "...";
}
print $body;
?>
luyendao’s picture

This is another function that does the same thing, but is cleaner, it was written by a friend programmer who know what he's doing.

function truncate($string, $limit, $break=".", $pad="...") {
if(strlen($string) <= $limit) return $string;

if(false !== ($breakpoint = strpos($string, $break, $limit))) {
if($breakpoint < strlen($string) - 1) {
$string = substr($string, 0, $breakpoint) . $pad;
}
}
return $string;
}

Usage would be, in a use case of a CCK field:
print truncate ($node->field_body_intro[0]['value'], 200, $break=".", #pad="...")

Where $break is equal to where it should truncate, i tend to use an empty space here if you want to get the exact character count, and the padding is self-explanatory. Super useful if you do any professional looking site with teasers...