Simple PHP Truncation

It’s a common issue: we want our dynamic text to fit nicely into our perfect design. But our client wants to use a title that’s two (or even three) lines long! This little snippet of code will save your design from unsightly overflow, and won’t cut off that last word mid-sente… [nce]

Subject Matter
Development

Author

Published
October 13, 2010

Share
Facebook Tweet

Here, we’re taking our title and using the variable $title. You can use any source you want, and it’s not restricted to just titles.

$title = "This is a ridiculously long title that never ends because there's a lot to say in a very long title and it just won't all fit on one line.";

Pull just the number of characters you want to use, then add 4 – 8 to account for the word you’ll be dropping.

$title = subtstr($title, 0, 40);

Now take your truncated string and make an array of words:

$title = explode(' ', $title);

Lose the last word, as it’s most likely cut off mid stride.

$useless = array_pop($title);

Now you can put it all back together and use whatever tail string you’d like.

$title = implode(' ', $title) . '...';

And there you go… a clean, truncated string that will now fit into your design safely.

If the title is shorter than the truncation string, you can wrap this whole function with:

$title = "This is a ridiculously long title that never ends because there's a lot to say in a very long title and it just won't all fit on one line.";
if ( strlen($title) > 36 ) {
  ::code goes here::
}

Note the string comparison length is 4 smaller than what we used to truncate above. This number is where we use the actual maximum character length to fit in your design. Enjoy!