Drupal 7 – Trim text programmatically

Drupal 7 provides the truncate_utf8() function for you to trim any string in PHP manually. Assume you have a lorem ipsum paragraph.

  • truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1)

$str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend velit in purus pharetra dictum. In hac habitasse platea dictumst. Sed convallis nunc quis massa posuere non hendrerit enim tempor. Morbi quis eros in lacus accumsan molestie. Maecenas euismod laoreet libero, a scelerisque dui varius aliquet. Mauris vitae augue augue, ac laoreet enim. Sed quis erat porttitor lectus eleifend feugiat. Aliquam erat volutpat. Vivamus aliquam ornare arcu at posuere. Pellentesque aliquet commodo ultricies. Nulla pellentesque nulla non nunc ultrices non pellentesque dolor consequat. Nunc vestibulum nisl feugiat sapien egestas tempus. Curabitur id enim elit.";

 

<?php print truncate_utf8($str, 30); ?>
RETURN: Lorem ipsum dolor sit amet, co
<?php print truncate_utf8($str, 30, TRUE); ?>
RETURN: Lorem ipsum dolor sit amet,
<?php print truncate_utf8($str, 30, TRUE, TRUE); ?>
RETURN: Lorem ipsum dolor sit amet,…

 

Please note that if the string contains HTML/PHP tags, you have to strip all tags before the calling truncate_utf8() or otherwise the HTML/PHP will be broken. For example:

  • <?php print truncate_utf8(strip_tags($str), 30, TRUE, TRUE); ?>

 

Done =)

Reference:

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s