How to add dots and shorten a string
TweetWhile working on the back-end Calcatraz management system, I came across a situation where I wanted to display strings, but if they were too long I wanted to truncate them and add three dots (ellipsis) to the end to show that this had occurred.
I first got on Google and looked for a solution. The best (as in most brief) solution I found could be distilled down to this:
(strlen($str)>10)?substr_replace($str,'...',10):$str;
(strlen($str)>10)?substr($str,0,10).'...':'';
preg_replace('/(.{10}).*/', '\\1...', $str);
This is shorter still, only uses the variable name once and is a single function call making it easier to spot the start and end. It’s not perfectly descriptive, but the second argument in particular does hint at it’s function. I’d be happy using this inline if it was only to be used a couple of times (and the surrounding code was otherwise quite straightforward).
Recommended Articles
Have you tried Calcatraz, our free online calculator? Examples: pi*10^2, 62kg in pounds and 1*2*3*4*5.

