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.
From stackoverflow
-
No it does not exist. Many libraries provide it however as you're not the first to need it. e.g. Smarty
-
It doesn't.
-
$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.
Jeremy DeGroot : That's no good because it appends the suffix to a string shorter than $maxLength.Ron DeVera : True, you'd still have to wrap it in your own function, which only runs substr_replace() based on that condition. -
Here's the one line version for those interested
<?php echo (strlen($string) > 40 ? substr($string, 0, 37)."..." : $string); ?>
Jeremy DeGroot : 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 resultTravisO : 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.Ólafur Waage : Of course, i agree. Hence my wording for those interested.outis : 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.
0 comments:
Post a Comment