An Interesting PHP Problem...


The Benevolent
I've been looking around the web and thinking about it, but I can't find the solution, though I know it's there somewhere.

Here's the problem. I've got a string, and let's say it contains the contents of an article on the site. I want to generate a preview of the article by getting the first 400 characters and displaying them followed by a "Read More" link.

That's easy enough. But the problem is, the article contains HTML. I need to know how to:

- Avoid splitting tags in half at the end of the preview, eg "Blah blah blah <a hre". That's bad.

- Close up any tags that remain open, eg "Blah blah <em>bla"...Notice that <em> is never closed.

I know there's a way to do this, because I've seen sites that do it. Anyone have any ideas?
I don't know the specific code to accomplis this (I don't speak PHP), but why don't you change all the carats to comment tags? Basically, just find a way to put an opening comment tag in front of every < and a closing comment tag behind every >. Like I said, I don't know the specifics of how to accomplish this, but if you comment out all the HTML tags you should be left with straight text.
Well, I'm already using strip_tags until I find a real solution to the problem. (arden, this is essentially what strip_tags solves). But my problem isn't getting rid of the tags. The problem is getting the first 400 characters of a string and making sure that no HTML was messed up in the process (ie, not splitting the string in the middle of a tag, and making sure that no tags remained open).
you'll have you count all the
then count all the >'s
and if you have 11 <'s
and if you have 10 >'s
then you need to go until you find the next >
so you change 400 to 410, or 412, or 398

it's not that hard.
Hi you can use this works fine
function cutting($news)


$cut = 400;

$ln = 20;

if ( strlen($news) > ($cut + $ln)) {

$before = substr($news,$cut-$ln,$ln);

$after = substr($news,$cut,$ln);

$pos = $cut;

if ( strrpos($before,".") ) $a = $ln - strrpos($before,".");

if ( strpos($after,".") ) $b = strpos($after,".");

if ( ($pos == $cut) && strrpos($before," ") ) $a = $ln-strrpos($before," ") ;

if ( ($pos == $cut) && strpos($after," ") ) $b = strpos($after," ");

if ($a > $b) {$pos = $cut + $b;}

else { $pos = $cut - $a; }

$cutting = substr($news,0,$pos);

$cutting .= " ...";


else { $cutting = $news;}

return $cutting;}

<? echo cutting($reg->news) ?>