truncate_utf8

Definition

truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE)
includes/unicode.inc, line 227

Description

Truncate a UTF-8-encoded string safely to a number of characters.

Parameters

$string The string to truncate.

$len An upper limit on the returned string length.

$wordsafe Flag to truncate at last space within the upper limit. Defaults to FALSE.

$dots Flag to add trailing dots. Defaults to FALSE.

Return value

The truncated string.

Code

<?php
function truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE) {

  if (drupal_strlen($string) <= $len) {
    return $string;
  }

  if ($dots) {
    $len -= 4;
  }

  if ($wordsafe) {
    $string = drupal_substr($string, 0, $len + 1); // leave one more character
    if ($last_space = strrpos($string, ' ')) { // space exists AND is not on position 0
      $string = substr($string, 0, $last_space);
    }
    else {
      $string = drupal_substr($string, 0, $len);
    }
  }
  else {
    $string = drupal_substr($string, 0, $len);
  }

  if ($dots) {
    $string .= ' ...';
  }

  return $string;
}
?>
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.