Norgul Norgul - 4 months ago 12
PHP Question

Laravel description formatting

I have a table of items which has description field. When listing out all items I would like to show exactly three rows of text followed by "..." if the text is longer.

I can do something like

<style>
.box {
overflow: hidden;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
-ms-text-overflow: ellipsis;
height: 60px;
}
</style>


...which works fine when there is a lot of text and the text is split in several lines. But if I have no new line chars in text I see only one line of text which is shortened.

Also if I have text formated like




Something

//blank-line

//blank-line

I am writing about something, because something is not nothing




I get my three lines...but it looks bad because first line is only "Something", and the two other are blank. So I figured I'd have to pre-format it before I send it from controller to view, and I tried first to approach that problem by removing empty lines and connecting whole text to one line, however this does nothing

$description = preg_replace( "/\r|\n/", "", $array[0]->description);
return $description


Which is maybe excepted since HTML formatted text enters the database

<p class="MsoNormal">Something<o:p></o:p></p>

<p class="MsoNormal"><o:p>&nbsp;</o:p></p>

<p class="MsoNormal">Blah blah...something else...


Does anyone have an idea how to solve this?

Answer

Naturally, text will flow to the next line when it reaches the edge of its container element in the browser. I assume your container's width is controlled by some styling (whether fixed or responsive).

So in your case I'd ditch the ellipsis styling, see (from physically looking in the browser) how many characters it takes to produce the 3 lines you desire, and then do (I also assume you don't want to keep the HTML):

$description = strip_tags($array[0]->description);

    if (strlen($description) > $maximumLength) {

        $description = substr($description, 0, $maximumLength) . "...";

    }

return $description

Of course there are other ways to do it on the client side with CSS or JavaScript, but what I see on most sites is they settle on a fixed length for their excerpt and just say any text longer than x characters mus be truncated.

Comments