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.