Drupal Tip #2 – Limiting long strings

Use truncate_utf8 to quickly limit strings to certain lengths, and define whether the break should occur at character level or word level. Also optionally appends ‘ …’. Point to take note is that the ‘ …’ would not add to the resultant length – drupal compensates it by limiting the original string 4 characters less. This would be obvious in the example below, as each output never exceeds the 20 character limit.

For example:

$sentence = 'a quick brown fox jumps over the lazy dog';
echo truncate_utf8($sentence, 20); //a quick brown fox ju
echo truncate_utf8($sentence, 20, TRUE); //a quick brown fox
echo truncate_utf8($sentence, 20, TRUE, TRUE); //a quick brown ...
echo truncate_utf8($sentence, 20, FALSE, TRUE); //a quick brown fo ...

// Output side-by-side:
//a quick brown fox ju
//a quick brown fox
//a quick brown ...
//a quick brown fo ...

Drupal 4.7 – 6:
truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE)

Drupal Api Reference: truncate_utf8

Leave a Reply

Your email address will not be published. Required fields are marked *