Skip to content

Instantly share code, notes, and snippets.

@odino
Created May 25, 2011 15:49
Show Gist options
  • Save odino/991219 to your computer and use it in GitHub Desktop.
Save odino/991219 to your computer and use it in GitHub Desktop.
<?php
function safe_truncate_text($text, $lenght)
{
$parts = explode(' ', $text);
$truncatedText = '';
$x = 0;
while(strlen($truncatedText) <= $lenght && $x < count($parts))
{
if (strlen($truncatedText) + strlen($parts[$x]) <= $lenght)
{
$truncatedText .= $parts[$x] . ' ';
}
$x++;
}
$text = rtrim($truncatedText);
return strlen($text) ? $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...');
@garak
Copy link

garak commented May 25, 2011

vai di preg_replace

@odino
Copy link
Author

odino commented May 25, 2011

Somebody on twitter suggested:
$s = preg_replace('/ [^ ]*$/', ' ...', $s);

but it does not work: since I suck at regex I need to spend some more time in this...

@julesbou
Copy link

There's a function in smarty to do this, maybe you can look at it.

@nsolsen
Copy link

nsolsen commented May 26, 2011

How about:

function safe_truncate_text($text, $length)
{
    $tmp = (strlen($text) == $length) ? $text : substr($text, 0, strrpos(substr($text, 0, $length), " "));
    return ($tmp != "") ? $tmp."..." : "";
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment