5

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.

4 Answers 4

5
$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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Here's the one line version for those interested

<?php 
    echo (strlen($string) > 40 ? substr($string, 0, 37)."..." : $string);
?>

3 Comments

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
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.
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.
2

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

Comments

1

It doesn't.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.