While working on the back-end Calcatraz management system, I came a cross a situation where I wanted to display strings, but if they were too long I wanted to truncate them and add three dots 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).