Created
February 17, 2011 23:44
-
-
Save cristobal/832992 to your computer and use it in GitHub Desktop.
Truncate Text
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
<?php | |
/** | |
* Truncate text | |
* | |
* @param $text | |
* @param $max | |
* @param $type | |
* @param $suffix | |
*/ | |
function truncate_text($text, $max = 100, $type = '', $suffix = '…') { | |
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