Jump to content

Parsing Strings with HTML Tags


apollo168

Recommended Posts

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! :-)

Link to comment
https://forums.phpfreaks.com/topic/45149-parsing-strings-with-html-tags/
Share on other sites

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);
?>

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...

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]

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.