Created
April 16, 2012 20:14
-
-
Save menslow/2401209 to your computer and use it in GitHub Desktop.
PHP: Couple of yummy truncate functions.
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
/** | |
* 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 . '…'; | |
} |
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
/** | |
* 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 . '…'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added some default checks.