Skip to content

Instantly share code, notes, and snippets.

@cbednarski
Created June 21, 2011 21:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbednarski/1038955 to your computer and use it in GitHub Desktop.
Save cbednarski/1038955 to your computer and use it in GitHub Desktop.
Truncates a string after n character, respecting word boundaries
<?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