hacker has asked for the wisdom of the Perl Monks concerning the following question:

I seem to recall the CB had this problem a few years ago, and it was solved... and now I'm running into it.

Here's the situation:

I have a database of news articles, which I query for 3 random entries. I clip the article summary at 200 characters and display the result. I'm using MySQL to clip the articles, like so:

$news_sth = $dbh->prepare (qq{ SELECT article_id, article_title, LEFT(article_body, 220) AS CLIP, DATE_FORMAT(article_date, '%W %M %D %Y') as my_date from news_articles group by article_id order by RAND() LIMIT 3});

This part works great... until 200 characters happens to fall right in the middle of an open HTML tag.

This is some random HTML from one of my <em>news articles that would be clipped...

Note in the above example, I've clipped after the opening <em> tag, but not after the matched closing tag.

What I'm trying to figure out, is...

  1. Should I be clipping with MySQL? Or substr() in Perl?
  2. Is there a way to "rewind" to the last open tag, so I can close it at the end of my clipped section?
  3. Another method?

The problem is most obvious when I'm clipping in the middle of a blockquote section or an ordered/unordered list. When the next article is drawn, it inherits the formatting left over from the previous open tag.


How should I best approach a fix for this?