Truncation

By Koolvin on Jan 20, 2011

This is a function that truncates input in a rather different way if I'm correct.
(I've never seen it done this way)

Usage: getTrunc("String",LENGTH);

What it does is first truncates the string the the given length, then explodes into an array by spaces, finally it removes the last key and impodes into a string.

function getTrunc($n, $l) {
    if ($l >= strlen($n)) { return $n; }
    $n = explode(' ', substr($n, 0, $l));
    if (count($n)>1) { unset($n[count($n)-1]); }
    return implode(' ', $n).'...';
}

Comments

Sign in to comment.
sunslayer   -  Feb 26, 2011

well you can always type cast it to string but that would probably take longer then just checking the length

 Respond  
bone282   -  Feb 26, 2011

yeah true, i was tired when i replied.
but who would pass an integer through that function. i suppose you could by getTrunc((string) $integer, 2);

but anyway, all i wanted to do was pass on the little - if (!isset($string{$count})){ - i like it and tbh it's pretty new to me :)

 Respond  
sunslayer   -  Feb 26, 2011
function getTrunc($n, $l) {
    if (!isset($n{$l}) { return $n; }
    $n = explode(' ', substr($n, 0, $l));
    if (count($n)>1) { unset($n[count($n)-1]); }
    return implode(' ', $n).'...';
}

your checking the size before its exploded, getTrunc(12345,2) will return 12345 instead of 12

 Respond  
bone282   -  Feb 26, 2011

the braces would be before the explode() array, have a look :)

 Respond  
sunslayer   -  Feb 26, 2011

i don't recommend using curly braces on arrays as they only work with strings, if you pass $n as an integer it will fail

 Respond  
bone282   -  Feb 24, 2011

One little tweek to make it a little faster is to use isset() instead of strlen(). This is because isset() is a language construct and not a function.

if ($l >= strlen($n)) return $n;
to:
if (!isset($n{$l})) return $n;

note using $string{$length} counts from zero.

 Respond  
bone282   -  Feb 09, 2011

looks quick n dirty, i like it

+like

 Respond  
Koolvin   -  Jan 20, 2011

I didn't think about that, and thanks for catching that mistake!

 Respond  
sunslayer   -  Jan 20, 2011
unset($n[$count($n)-1]);

should be

unset($n[count($n)-1]);

you also have two ;'s on the following line

also if there are no spaces then this will only return '...'

if(count($n)>1) unset($n[count($n)-1]);
 Respond  
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.