Skip to content

Instantly share code, notes, and snippets.

@melat0nin
Created February 6, 2012 11:52
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 melat0nin/1751730 to your computer and use it in GitHub Desktop.
Save melat0nin/1751730 to your computer and use it in GitHub Desktop.
PHP: Truncate text to x chars
function truncate($string,$words) {
$truncated = preg_replace('/((\w+\W*){' . $words . '}(\w+))(.*)/', '${1}', $string);
if ( strlen($string) > strlen($truncated) ) {
$truncated .= '...';
}
return $truncated;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment