You are here

function drupal_truncate_bytes in Drupal 6

Same name and namespace in other branches
  1. 7 includes/unicode.inc \drupal_truncate_bytes()

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

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.

Return value

The truncated string.

1 call to drupal_truncate_bytes()
mime_header_encode in includes/unicode.inc
Encodes MIME/HTTP header values that contain non-ASCII, UTF-8 encoded characters.

File

includes/unicode.inc, line 208

Code

function drupal_truncate_bytes($string, $len) {
  if (strlen($string) <= $len) {
    return $string;
  }
  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);
}