Category Archives: Drupal

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

Drupal Tip #1 – Formating Time Ago

Drupal has a nice little function called format_interval that formats a time interval in a “x secs ago” fashion. Note that it accepts a time interval, not an absolute time value, thus you need to subtract the time value from time().

For example, to print your node’s created time, use:

<?php echo 'Submitted ',format_interval(time()-$node->created),' ago'; ?>

Drupal API ref for format_interval()