apollo168 Posted April 1, 2007 Share Posted April 1, 2007 Basically I have some articles written with a WYSIWYG editor that are stored in the DB with the HTML tags. I successfully call the DB to get my text, and I want to truncate the length of the text to a certain point for showing preview articles. My problem is that simply using substr() can sometimes chop off the string in the middle of an HTML tag leaving a nasty mess. Does anyone have any suggestions on how to parse the string correctly to avoid truncating in the middle of an HTML tag? Thanks for the help! :-) Quote Link to comment Share on other sites More sharing options...
Barand Posted April 1, 2007 Share Posted April 1, 2007 Here's one from my library <?php function truncateWithTags($text, $numchars) { $copy = ''; $len = strlen($text); if ($len <= $numchars) return $text; $count = 0; $intag = 0; for ($i=0; $i<$len; $i++) { $c = $text{$i}; switch ($c) { case '<': $copy .= $c; $intag = 1; break; case '>': $copy .= $c; $intag = 0; break; default: if ($intag) $copy .= $c; else { if ($count < $numchars) { $copy .= $c; } elseif ($count == $numchars) { $copy .= '... '; } ++$count; } } #switch } #for return $copy; } $text = "<strong>Hello</strong> today is a <strong>beautiful</strong> day because I can get this function to work"; echo truncateWithTags($text, 30); ?> Quote Link to comment Share on other sites More sharing options...
apollo168 Posted April 3, 2007 Author Share Posted April 3, 2007 That does a nice job at checking if you're in HTML, but what about if the text gets truncated and you leave a tag hanging open without including it's close tag? For example, if you had truncated in between your <strong> tags, everything after that preview article would be in bold... Quote Link to comment Share on other sites More sharing options...
Barand Posted April 3, 2007 Share Posted April 3, 2007 Don't knock it till you've tried it. $text = "<strong>Hello</strong> today is a <strong>beautiful day because I can get this function to work</strong>"; echo truncateWithTags($text, 30); --> [pre] <strong>Hello</strong> today is a <strong>beautiful day... </strong> [/pre] Quote Link to comment Share on other sites More sharing options...
apollo168 Posted April 3, 2007 Author Share Posted April 3, 2007 Hahaha, dang it! The ultimate call out! :-) It seems to be working awesome, thanks man!!! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.