0

The context: Picture a stream of article previews which when clicked will lead away to their own pages(irrelevant).

Each preview will include a title and a sample of the content(string) from the top of the represented article with an appended 'read more' anchor. Simple example at the bottom.

My goal: To truncate any text exceeding the width of the preview container. The title being one line and content three lines.

Now, I'm not particularly sure that PHP is capable of trimming strings based on the containers width. I do know however, that it is possible to trim a set amount of characters like this. My code is similar...

// $data is an associate array full of stuff

foreach ($data as $key => $row) {
    $data[$key]['artcl_trunc_title'] 
        = (strlen($row['artcl_title']) > 100) ? $trimmed = substr($row['artcl_title'], 0, 100) . '..' : $row['artcl_title'];



    $data[$key]['artcl_trunc_content'] 
        = (strlen($row['artcl_content']) > 300) ? substr($row['artcl_content'], 0, 300) . '.. <a href="">READ MORE</a>' : $row['artcl_content'];
}

The problem with it is that text is trimmed based on a set figure. This wouldn't be a problem except for the fact that not all characters are the same width. Look at the following example (Both lines are 20 characters.)

....................

WWWWWWWWWWWWWWWWWWWW

Now, here is a real example of the problem (both articles have the same theoretical character cap... Title 20, content 50)

The Lonesome Gentlem..

So there is this kid who never leaves his house an.. READ MORE

-

WainWright's Guide t..

I've written this guide to help those who have pro.. READ MORE

This doesn't look too bad here, but you can see that the length is different between the two contents and titles. It's a nightmare when scaled up and you're trying to fill a set amount of lines exactly (as sometimes lines can appear or disappear depending on the characters used.)

Also, I'm not keen on using css overflow:hidden as text sometimes gets cut in half.

So.. any ideas on how to approach this, or best practices? Thanks

TL;DR: As the title says.

Community
  • 1
  • 1
user2950370
  • 117
  • 3
  • 13
  • 1
    Without reading your whole question I think : 1- this has been asked several times 2- just use CSS – HamZa Feb 02 '14 at 23:45

1 Answers1

0

I would do this with CSS using the text-overflow: ellipsis; directive.

Jon
  • 10,678
  • 2
  • 36
  • 48