tags:

views:

305

answers:

4

I found myself needing this function, and was wondering if it exists in PHP already.

/**
 * Truncates $str and returns it with $ending on the end, if $str is longer
 * than $limit characters
 *
 * @param string $str
 * @param int $length
 * @param string $ending
 * @return string
 */
function truncate_string($str, $length, $ending = "...")
{
    if (strlen($str) <= $length)
    {
     return $str;
    }
    return substr($str, 0, $length - strlen($ending)).$ending;
}

So if the limit is 40 and the string is "The quick fox jumped over the lazy brown dog", the output would be "The quick fox jumped over the lazy brow...". It seems like the sort of thing that would exist in PHP, so I was surprised when I couldn't find it.

+1  A: 

No it does not exist. Many libraries provide it however as you're not the first to need it. e.g. Smarty

Macha
+1  A: 

It doesn't.

Koistya Navin
+5  A: 
$suffix = '...';
$maxLength = 40;

if(strlen($str) > $maxLength){
  $str = substr_replace($str, $suffix, $maxLength);
}

Your implementation may vary slightly depending on whether the suffix's length should be count towards the total string length.

Ron DeVera
That's no good because it appends the suffix to a string shorter than $maxLength.
Jeremy DeGroot
True, you'd still have to wrap it in your own function, which only runs substr_replace() based on that condition.
Ron DeVera
+4  A: 

Here's the one line version for those interested

<?php 
    echo (strlen($string) > 40 ? substr($string, 0, 37)."..." : $string);
?>
Ólafur Waage
That was my first response, too. Subtract the length of your suffix from your string length though, or else you'll have a 43-character result
Jeremy DeGroot
Good work but imho it's better to use easy to read code than ternary code, unless it's an extreme speed situation where you're looping this a million times.
TravisO
Of course, i agree. Hence my wording for those interested.
Ólafur Waage
The ternary operator doesn't give a speed advantage over an if-else block. The main advantage of ?: is that, unlike if-else, it is an expression and can be used where if-else is syntactically invalid.
outis