0

This guy: https://stackoverflow.com/a/7239020/2453678 posted a great answer here: http://jsfiddle.net/imoda/REs2Q/

Basically, if you want a elegant solution, counting the number of characters is out of question, as each letter has different weight.

The question is:

span {
    display: inline-block;
    border: black 1px solid;
    width: 200px;
    height: 40px;
    overflow: hidden;
}

How to modify the above code, so at the end, if the string is shortened, three '.' are added?

Community
  • 1
  • 1
  • There’s `text-overflow`, but [it can only handle one line comfortably](http://jsfiddle.net/rninty/REs2Q/249/). – rninty Nov 09 '13 at 23:47

1 Answers1

1

I've coded a simple function in PHP.

function limit_text($input, $n){
    $array = preg_split('~\R+~', $input);       // Split by newline(s)
    $array = array_slice($array, 0, $n);        // Get the first n parts
    $output = implode('<br>', $array) . '...';  // Implode and add some dots
    return $output;
}

Here's how you use it:

$str = 'span {
    display: inline-block;
    border: black 1px solid;
    width: 200px;
    height: 40px;
    overflow: hidden;
}';

echo '<pre>' . limit_text($str, 2); . '</pre>';
HamZa
  • 14,671
  • 11
  • 54
  • 75
  • Outstanding, but, how can I limit the line width? –  ShadowHero Nov 10 '13 at 00:09
  • @ShadowHero Well I'm re-reading your question and I'm wondering why you tagged it as "PHP" ? Maybe you meant CSS ? As for the line width, that's possible, we could limit a line to say 50 characters. But would those 50 + 50 + 50 characters make sense when combined ? – HamZa Nov 10 '13 at 00:11
  • You are correct, the question is css for sure and maybe php, depending on the way you solve it. As for the line width, I am trying to make it work with pixels, e.g. 150px. –  ShadowHero Nov 10 '13 at 00:15
  • @ShadowHero Then just forget about PHP. Since it all depends on the font type, size, style etc... – HamZa Nov 10 '13 at 00:17
  • Is what I am trying to do possible? –  ShadowHero Nov 10 '13 at 00:18
  • I mean, if it's impossible with php, the only other way is css. But css doesn't add characters... –  ShadowHero Nov 10 '13 at 00:21
  • @ShadowHero [Sure you can](http://jsfiddle.net/F5dmS/), but not in your case ... Well at the moment I don't have a solution for you .., – HamZa Nov 10 '13 at 00:35