Skip to content

Instantly share code, notes, and snippets.

@ashrewdmint
Created January 14, 2010 21:33
Show Gist options
  • Save ashrewdmint/277528 to your computer and use it in GitHub Desktop.
Save ashrewdmint/277528 to your computer and use it in GitHub Desktop.
Smart character limit functions for PHP
// Intelligently truncate a string to a certain number of characters.
// Each uppercase or wider-than-normal character reduces the final length.
function truncate($string, $length, $ellipsis = true) {
// Count all the uppercase and other wider-than-normal characters
$wide = strlen(preg_replace('/[^A-Z0-9_@#%$&]/', '', $string));
// Reduce the length accordingly
$length = round($length - $wide * 0.2);
// Condense all entities to one character
$clean_string = preg_replace('/&[^;]+;/', '-', $string);
if (strlen($clean_string) <= $length) return $string;
// Use the difference to determine where to clip the string
$difference = $length - strlen($clean_string);
$result = substr($string, 0, $difference);
if ($result != $string and $ellipsis) {
$result = add_ellipsis($result);
}
return $result;
}
// Replaces the last 3 characters of a string with "...". If there is a space
// followed by three letters or less at the end of the string, those will
// also be removed, along with any extra white space.
function add_ellipsis($string) {
$string = substr($string, 0, strlen($string) - 3);
return trim(preg_replace('/ .{1,3}$/', '', $string)) . '...';
}
// Truncates a string and guarantees it will display at a maximum number
// of lines (spaces are inserted if necessary so that the string will wrap).
// Uses the truncate() function so uppercase or wider-than-normal characters
// actually make the final string shorter, for layout reasons.
function truncate_lines($string, $line_length, $lines, $ellipsis = true) {
$result = '';
$spaces_added = 0;
// Divide up the string into lines
for ($i=0;$i<$lines;$i++) {
if (! $next_start) {
$start = $i * $line_length;
} else {
$start = $next_start;
}
$line = substr($string, $start, $line_length + 1);
// Truncate the line by the appropriate length
$old_line = $line;
$line = truncate($line, $line_length, false);
$difference = strlen($old_line) - strlen($line);
$next_start = (($i + 1) * $line_length) - $difference + 1;
// If there are no line breaks in this line at all
if (strlen($line) < strlen($string) and ! strstr($line, ' ')) {
// Add a space to it, keep track of how many spaces are added
$line .= ' ';
$spaces_added ++;
}
$result .= $line;
}
$result = substr($result, 0, strlen($result) - $spaces_added);
if ($result != $string and $ellipsis) {
$result = add_ellipsis($result);
}
return $result;
}
@saratonite
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment