Skip to content

Instantly share code, notes, and snippets.

@menslow
Created April 16, 2012 20:14
Show Gist options
  • Save menslow/2401209 to your computer and use it in GitHub Desktop.
Save menslow/2401209 to your computer and use it in GitHub Desktop.
PHP: Couple of yummy truncate functions.
/**
* truncate_words function to truncate a string of words to a specified number of words
* @param string $str The text string to split
* @param integer $words The number of words to extract. Defaults to 15
*/
function truncate_words( $str, $words = 15 )
{
$arr = preg_split( '/[\s]+/', $str, $words+1 );
$arr = array_slice( $arr, 0, $words );
return join( ' ', $arr ) . '…';
}
/**
* truncate_chars function to truncate a string of chars to a specified number of chars
* @param string $str The text string to split
* @param integer $chars The number of chars to extract. Defaults to 15
*/
function truncate_chars( $chars, $len = 15 )
{
$i = strlen($chars);
if($i <= $len)
{
return $chars;
}
$chars = substr($chars, 0, $len);
return $chars . '&hellip;';
}
/**
* truncate_words function to truncate a string of words to a specified number of words
* @param string $str The text string to split
* @param integer $words The number of words to extract. Defaults to 15
*/
function truncate_words( $str, $words = 15 )
{
$arr = preg_split( '/[\s]+/', $str, $words+1 );
$arr = array_slice( $arr, 0, $words );
return join( ' ', $arr ) . '&hellip;';
}
/**
* truncate_chars function to truncate a string of chars to a specified number of chars
* @param string $str The text string to split
* @param integer $chars The number of chars to extract. Defaults to 15
*/
function truncate_chars( $chars, $len = 15 )
{
$i = strlen($chars);
if($i <= $len)
{
return $chars;
}
$chars = substr($chars, 0, $len);
return $chars . '&hellip;';
}
@menslow
Copy link
Author

menslow commented Apr 16, 2012

Added some default checks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment