Skip to content

Instantly share code, notes, and snippets.

@phylsys
Created July 24, 2014 17:35
Show Gist options
  • Save phylsys/fbda68b8e78803dca813 to your computer and use it in GitHub Desktop.
Save phylsys/fbda68b8e78803dca813 to your computer and use it in GitHub Desktop.
A better PHP trim() function
/**
* trims text to a maximum length, splitting at last word break, and (optionally) appending ellipses and stripping HTML tags
* @param string $input text to trim
* @param int $length maximum number of characters allowed
* @param bool $ellipses if ellipses (...) are to be added
* @param bool $strip_html if html tags are to be stripped
* @return string
*/
function trim_better($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//strip leading and trailing whitespace
$input = trim($input);
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//leave space for the ellipses (...)
if ($ellipses) {
$length -= 3;
}
//this would be dumb, but I've seen dumber
if ($length <= 0) {
return '';
}
//find last space within length
//(add 1 to length to allow space after last character - it may be your lucky day)
$last_space = strrpos(substr($input, 0, $length + 1), ' ');
if ($last_space === false) {
//lame, no spaces - fallback to pure substring
$trimmed_text = substr($input, 0, $length);
}
else {
//found last space, trim to it
$trimmed_text = substr($input, 0, $last_space);
}
//add ellipses (...)
if ($ellipses) {
$trimmed_text .= '...';
}
return $trimmed_text;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment