Calculator Typist Blog

How to add dots and shorten a string

While 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;

It’s a bit clumsy, and contains the variable name three times, so would become quite long if the variable name was itself long. It would probably be best wrapped in a function to keep things clean, even if only used once or twice. I decided to try and do better. My first attempt was:

(strlen($str)>10)?substr($str,0,10).'...':'';
It’s shorter and only contains the variable name two times. However, it’s still not great. If it was inlined in code it is difficult to spot where it starts and finishes, so again wrapping it in a function call would probably be the best way to go.
I then realised I could achieve the same thing  with a single call to preg_replace(), like so:

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.



Post Metadata

Date
March 6th, 2010

Author
admin

Category

Tags


Comments are closed.