user962449
user962449

Reputation: 3873

php character limits (trim an html paragraph)

We have our own blog system and the post data is stores a raw html, so when it's called from the db we can just echo it and it's formatted completely, no need for BB codes in our situation. Our issue now is that our blog posts sometimes are too long and need to be trimmed.

The problem is that our data contains html, mostly <font>, <span>, <p>, <b>, and other styling tags. I made a php function that trims the characters, but it doesn't take into account the html tags. If the trim function trims the blog it should not trim tags because it messes the whole page. The function needs to be able to close the html tags if they're trimmed. Is there a function out there that can do this? or a function where I could start and build from it?

Upvotes: 2

Views: 1524

Answers (4)

Eli
Eli

Reputation: 99428

I know this isn't the best way to do it programatically, but have you considered manually specifying where the cut should be? Adding something like and cutting it there manually would allow you to control where the cut happened, regardless of the number of characters before it. For example, you could always put that below the first paragraph.

Admittedly, you lose the ability to just have it happen automatically, but I bring it up in case that doesn't matter as much to you.

Upvotes: 0

Sam Starling
Sam Starling

Reputation: 5378

There's a good example here of truncating text while preserving HTML tags.

Upvotes: 2

Borealid
Borealid

Reputation: 98489

The right solution is to not store display information in your database layer.

Failing that, you could use CSS overflow properties: print the whole post, and then have the display layer handle sizing it to fit. This mitigates the problem of having formatting information in your database by putting the resizing (a display issue, not a content issue) into the display layer as well.

Failing that, you could parse the HTML and "round up" or "round down" to the nearest tag boundary, then insert the tag-close characters necessary to finish the block you were in.

Another option is to iframe the content.

Upvotes: 2

Halcyon
Halcyon

Reputation: 57729

There is strip_tags which gets rid of all HTML tags but other than that there isn't much.

This is not an easy thing by the way, you have to actually parse the HTML to find out which tags are left open - that's the most robust approach anyway. Also, don't use a regular expression.

Upvotes: 2

Related Questions