Keep the first two text lines, delete everything else

In the <div> I have text. Due to div -width, text is displayed in multiple lines. For instance. following code:

 <div>text01 text02 text03 text04 text05 text06 text07 text08 text09 text10 text11 text12</div> 

four lines can be shown, for example:

 text01 text02 text03 text04 text05 text06 text07 text08 text09 text10 text11 text12 

I want to save only the first two lines, and if further lines are present, they should be deleted and replaced with a text line ... as a new (therefore third) text line.
In other words: I want to find the second line break (if any) and replace all the text after this point with a text line containing ...

So, if I have two lines of text, nothing changes:

 text text text text text text 

But if I have more than two lines as above, I will get this:

 text01 text02 text03 text04 text05 text06 ... 

Any good advice?

+6
source share
3 answers

You should do this in css and add javascript if necessary.

In css you can install:

 .two-line-div { max-height: 3em; /* or whatever adds up to 2 times your line-height */ overflow: hidden; } 

This will reduce the pitch to the desired height.

If you always want to show ... (if the content is always more than two lines), just add an element with three dots after the div .

If you want to add another line with ... if the content is larger than what you are showing, you will need javascript to calculate the original height, see if it is more than two lines, and add / show the element dynamically if there is one.

Please note that the css solution does not delete anything, all the lines are there, they are simply not visible.

+5
source

Most modern browsers have a clean CSS solution (some older versions of firefox do not support it):

 div { overflow: hidden; /* "overflow" value must be different from "visible" */ text-overflow: ellipsis; /* the magic dots...*/ height: <yourHeightValue> width: <yourWidthValue> } 

Doing something like this in PHP might be a little more complicated, depending on what the DIV contains (nested HTML ?, what is a "line" to you -> HTML break, line break \ n)? In most cases, PHP solutions are split after a certain length of String or Word. You can find quite a few examples for this kind of text restriction; this one is a complex solution that can also handle html tags.

0
source

You can use explode() to split your string ( div content) into an array. Use <br> or /n as a separation token. Then you can replace the contents of the div with the first two elements of the array.

 $content = 'Hello<br>World<br>Other<br>Stuff'; $lines = explode('<br>',$content,2); echo '<div>'$lines[0].'<br>'.$lines[1].'<br>...</div>' 
-1
source

All Articles