Tuesday, October 28, 2014

Truncating a string on a word boundary in Drupal

Typical task: "truncate a string only on a word boundary and add a some postfix to resulting string". Every developer did it many times, I'm sure. Here is a how Drupal solves it with it's api: function views_trim_text
define(MAX_LENGTH, 30);

$alter = array(
    'max_length' => MAX_LENGTH,
    'word_boundary' => TRUE,
    'ellipsis' => TRUE
);

$mystring = "truncate a string only on a word boundary and add a some postfix to resulting string";
$mystring = views_trim_text($alter, $mystring); //result is 'truncate a string only on a...'

No comments :