Skip to content

Instantly share code, notes, and snippets.

@fabiocicerchia
Forked from odino/truncatetext.php
Created May 25, 2011 17:35
Show Gist options
  • Save fabiocicerchia/991444 to your computer and use it in GitHub Desktop.
Save fabiocicerchia/991444 to your computer and use it in GitHub Desktop.
<?php
function safe_truncate_text($text, $lenght)
{
$trailingDots = '';
$truncatedText = substr($text . ' ', 0, $lenght);
if (strlen($text) > $lenght)
{
$truncatedText = preg_replace('/ [^ ]+$/', '', ' ' . $truncatedText);
$truncatedText = trim($truncatedText);
$trailingDots = !empty($truncatedText) ? '...' : '';
}
return $truncatedText . $trailingDots;
}
/// 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...'); // Fail: I don't think that an undersized string when truncated has the trailing dots
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment