Skip to content

Instantly share code, notes, and snippets.

@aj-justo
Forked from odino/truncatetext.php
Created May 26, 2011 19:17
Show Gist options
  • Save aj-justo/993835 to your computer and use it in GitHub Desktop.
Save aj-justo/993835 to your computer and use it in GitHub Desktop.
aj safe truncate text try!
<?php
function safe_truncate_text($text, $lenght)
{
$trunc_text_parts = explode(' ', substr($text, 0,$length));
$parts = count($trunc_text_parts);
$final_text_parts = array_slice( explode(' ', $text), 0, $parts );
$final_text = implode(' ', $final_text_parts).' ...';
return $final_text;
}
/// TEST
$text = "Text Text Text Text Text ";
$t->is(safe_truncate_text($text, 10), 'Text Text...');
$t->is(safe_truncate_text($text, 1), '');
$t->is(safe_truncate_text($text, 12), 'Text Text...');
$t->is(safe_truncate_text($text, 15), 'Text Text Text...');
$t->is(safe_truncate_text('The quick', 2), '');
$t->is(safe_truncate_text('The quick', 4), 'The...');
$t->is(safe_truncate_text('The quick', 6), 'The...');
$t->is(safe_truncate_text('The quick', 9), 'The quick...');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment