Created
June 21, 2011 21:32
-
-
Save cbednarski/1038955 to your computer and use it in GitHub Desktop.
Truncates a string after n character, respecting word boundaries
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 | |
/** | |
* Truncates $string after $length characters, without splitting words. | |
* | |
* Inspired by http://stackoverflow.com/questions/250357 | |
* | |
* @param string $string | |
* @param integer $length | |
* @return string | |
*/ | |
function smartTruncate($string, $length) | |
{ | |
if(strlen($string) <= $length) | |
{ | |
return $string; | |
} | |
else | |
{ | |
$bits = explode(' ', substr($string, 0, $length)); | |
array_pop($bits); | |
$string = implode(' ', $bits); | |
return $string; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment