| 5 unicode.inc | truncate_utf8($string, $len, $wordsafe = FALSE, $dots = FALSE) |
| 6 unicode.inc | truncate_utf8($string, |
| 7 unicode.inc | truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) |
| 8 unicode.inc | truncate_utf8($string, $max_length, $wordsafe = FALSE, $add_ellipsis = FALSE, $min_wordsafe_length = 1) |
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.
File
- includes/
unicode.inc, line 233
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;
}
?> Login or register to post comments
Comments
Truncate at end of sentence
To truncate at the end of a sentence, which is a nice and clean alternative, use the text_summary() function.
It's a little hard to track that function down since due to the name, super useful though.