Skip to content

Instantly share code, notes, and snippets.

@kdimatteo
Created October 25, 2013 15:20
Show Gist options
  • Save kdimatteo/7156410 to your computer and use it in GitHub Desktop.
Save kdimatteo/7156410 to your computer and use it in GitHub Desktop.
Truncate a string without spitting on a word, and without any trailing punctuation from the original string. (PHP)
function str_truncate($string, $length) {
$bogus = array(",", ".", "?", "!", ";", "/", "$", "%", "*", "&", "#", "+", "=");
if (strlen($string) > $length) {
$string = substr($string, 0, ($length -3));
$string = substr($string, 0, strrpos($string, ' '));
if(in_array(substr($string, -1), $bogus)){
$string = substr($string, 0, strlen($string)-1);
}
$string .= "...";
}
return $string;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment