Created
December 11, 2014 19:11
-
-
Save henriqueboaventura/224241571c13bfb3aa36 to your computer and use it in GitHub Desktop.
limit string without cutting word
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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