Skip to content

Instantly share code, notes, and snippets.

@henriqueboaventura
Created December 11, 2014 19:11
Show Gist options
  • Save henriqueboaventura/224241571c13bfb3aa36 to your computer and use it in GitHub Desktop.
Save henriqueboaventura/224241571c13bfb3aa36 to your computer and use it in GitHub Desktop.
limit string without cutting word
<?php
/**
* trims text to a space then adds ellipses if desired
* @param string $input text to trim
* @param int $length in characters to trim to
* @param bool $ellipses if ellipses (...) are to be added
* @param bool $strip_html if html tags are to be stripped
* @return string
*/
function trim_text($input, $length, $ellipses = true, $strip_html = true) {
//strip tags, if desired
if ($strip_html) {
$input = strip_tags($input);
}
//no need to trim, already shorter than trim length
if (strlen($input) <= $length) {
return $input;
}
//find last space within length
$last_space = strrpos(substr($input, 0, $length), ' ');
$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