truncate_utf8

Versions
4.6
truncate_utf8($string, $len, $wordsafe = FALSE)
4.7 – 7
truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE)

Truncate a UTF-8-encoded string safely.

If the end position is in the middle of a UTF-8 sequence, it scans backwards until the beginning of the byte sequence.

Use this function whenever you want to chop off a string at an unsure location. On the other hand, if you're sure that you're splitting on a character boundary (e.g. after using strpos() or similar), you can safely use substr() instead.

Parameters

$string The string to truncate.

$len An upper limit on the returned string length.

$wordsafe Flag to truncate at nearest space. Defaults to FALSE.

Return value

The truncated string.

Related topics

▾ 9 functions call truncate_utf8()

aggregator_parse_feed in modules/aggregator.module
comment_admin_overview in modules/comment.module
Menu callback; present an administrative comment listing.
comment_validate_form in modules/comment.module
format_name in includes/common.inc
Format a username.
mime_header_encode in includes/common.inc
Encodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded characters.
node_teaser in modules/node.module
Automatically generate a teaser for a node body in a given format.
search_excerpt in modules/search.module
Returns snippets from a piece of text, with certain keywords highlighted. Used for formatting search results.
watchdog_overview in modules/watchdog.module
Menu callback; displays a listing of log messages.
_search_keywords_truncate in modules/search.module
Helper function for array_walk in search_keywords_split.

Code

includes/common.inc, line 1724

<?php
function truncate_utf8($string, $len, $wordsafe = FALSE) {
  $slen = strlen($string);
  if ($slen <= $len) {
    return $string;
  }
  if ($wordsafe) {
    $end = $len;
    while (($string[--$len] != ' ') && ($len > 0)) {};
    if ($len == 0) {
      $len = $end;
    }
  }
  if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {
    return substr($string, 0, $len);
  }
  while (--$len >= 0 && ord($string[$len]) >= 0x80 && ord($string[$len]) < 0xC0) {};
  return substr($string, 0, $len);
}
?>
Login or register to post comments
 
 

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.