Skip to content

Instantly share code, notes, and snippets.

@cristobal
Created February 17, 2011 23:44
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 cristobal/832992 to your computer and use it in GitHub Desktop.
Save cristobal/832992 to your computer and use it in GitHub Desktop.
Truncate Text
<?php
/**
* Truncate text
*
* @param $text
* @param $max
* @param $type
* @param $suffix
*/
function truncate_text($text, $max = 100, $type = '', $suffix = '&hellip;') {
if($type == 'exact'){
return (strlen($text) > $max ? substr($text, 0, $max) . $suffix : $text);
}
else if ($type == 'max+words') {
$words = explode(' ', $text);
$content = array_shift($words);
if (strlen($content) < $max) {
foreach ($words as $word) {
$word = array_shift($words);
$count = strlen($word) + strlen($content) + 1;
if ($count > $max) {
array_push($words, $word);
break;
}
$content .= ' ' . $word;
}
}
}
else {
$words = explode(' ', $text);
$content = array_shift($words);
if (strlen($content) < $max) {
foreach ($words as $word) {
$content .= ' ' . array_shift($words);
if (strlen($content) >= $max) {
break;
}
}
}
}
return $content . ( empty($words) ? '' : $suffix);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment