Hello all,

I wanted to know if anyone knows how to truncate a string with HTML code in it. I need to truncate the string to various characters but I dont want to count the html tags. Is this possible?

my truncate script as is

function truncate_string($string, $max_length){
    if (strlen($string) > $max_length) {
         $string = substr($string,0,$max_length);
         $string .= '...';
    }
return $string;
}

thanks
DP

    Well, one thing you could do is use [man]strip_tags/man and save that as a new variable. You can then cut that string to X characters. Then you just have to go back, find the place you end the line, and close any open HTML tags....

      I have a form that uses a WYSIWYG text editor, so certain tags are in html format and stored into mysql. I then post that to another page, but if the text is to long I need to truncate it but I don't want the php script to count the html tags just the actual text the user typed in.

      Stripping all tags would take away the format of how it will be displayed.

        You're missing what I said. If you do:

        $some_other_var = strip_tags($_POST['text']);

        Then $some_other_var will have the text the user wrote. From there, you can count the characters and stop after $length:

        $some_other_var = substr($some_other_var, 0, $len);

        Now, you just need to find the instance of that in your original var...

        // Use the last 10 characters.... you could shorten this if you'd like
        $position = strpos($_POST['text'], substr($some_other_var, -10));

        if($position === false)
        die('Error finding sub-string');[/code]

        Once you have the position, you can then cut the original string there:

        $cut_text = substr($_POST['text'], 0, $position);

        Then you just need to go through and find all the opening tags, and then find their closing tags (if applicable). Things you need to watch out for are <img> tags (which don't have a closing tag) and those that are empty. So you'd need to find all tags that don't have a "/>" as the last two characters. Then you'd just need to have as many closing tags of that element that you do the opening.

        You still preserve the text, but you just use other variables to do the "chopping".

          4 years later

          I realize that this is a little late but thought you might have some interest in spinning and truncating your article for web usage so that you don't cut it off in the middle of a sentence or paragraph and that you will get a good uniqueness of over 30% on a consistent basis without having to redo your articles every week.

          Should someone come up with changes or a better way to handle this please do...Otherwise I hope you like what I put together and found..

          <?php
          /
          $pass : The spinned text to un-spin
          /

          function Spin($pass){
              $mytext = $pass;
              while(inStr("}",$mytext)){
                  $rbracket = strpos($mytext,"}",0);
                  $tString = substr($mytext,0,$rbracket);
                  $tStringToken = explode("{",$tString);
                  $tStringCount = count($tStringToken) - 1;
                  $tString = $tStringToken[$tStringCount];
                  $tStringToken = explode("|",$tString);
                  $tStringCount = count($tStringToken) - 1;
                  $i = rand(0,$tStringCount);
                  $replace = $tStringToken[$i];
                  $tString = "{".$tString."}";
                  $mytext = str_replaceFirst($tString,$replace,$mytext);
              }
              return $mytext;
          }
          
          function str_replaceFirst($s,$r,$str){
              $l = strlen($str);
              $a = strpos($str,$s);
              $b = $a + strlen($s);
              $temp = substr($str,0,$a) . $r . substr($str,$b,($l-$b));
              return $temp;
          }
          
          function inStr($needle, $haystack){
              return @strpos($haystack, $needle) !== false;
          }  

          /
          $string : The original string to truncate
          $limit : The number words to truncate to, may well be over a little due to it ending on the paragraph boundary and not the word boundary.
          /

          function myTruncate($string, $limit) { 
              // return with no change if string is shorter than $limit 
              $WC = str_word_count($string);
              $NWC = 0;
              $ReturnString = null;
              if($WC <= $limit) return $string; 
              while( $NWC < $limit ){
                  // Find percent of total vs $limit 
                  $PerC = $limit / $WC;
                  // Find First Paragraph ending
                  $Para = stripos($string,"\r\n");
                  if( $Para ){
                      $NewString = substr($string,0,$Para+2);
                      $string = str_ireplace($NewString,"",$string);
                      $string = ltrim($string);
                      $NWC += str_word_count($NewString);
                  }
                  if( str_word_count($NewString) > 10 ){
                      // Add in your own formatting for the paragraphs
                      $ReturnString .= "<p style='line-height:normal'><span style='font-size:12.0pt;font-family:\"Times New Roman\",\"serif\"; color: black;'>{$NewString}</span></p>";
                  }
                  else{
                      $ReturnString .= "<p style='line-height:normal'><span style='font-size:12.0pt;font-family:\"Times New Roman\",\"serif\"; color: black;'><b>{$NewString}</b></span></p>";
                  }
              } 
              return $ReturnString; 
          }

          ?>

          Usage:

          $Title = "{Which|What|Exactly which|Generally} {Diaper|Baby diaper|Nappy} {to|for you to|to actually|to positively} {Choose|Select|Pick|Decide on|Opt for}?";
          $SpunArticle = myTruncate(Spin($Title),600);
          echo $Article . $SpunArticle;

            $Title = "{Which|What|Exactly which|Generally} {Diaper|Baby diaper|Nappy} {to|for you to|to actually|to positively} {Choose|Select|Pick|Decide on|Opt for}?";

            $Article = 
            "<p class=MsoNormal align=center style='margin-bottom:0in;margin-bottom:.0001pt;text-align:center;line-height:normal'><span style='font-size:18.0pt;font-family:\"Times New Roman\",\"serif\";color: red;'><b><i>" . Spin($Title) . "</i></b></span></p>";

            $Article1 = "{Think|Believe|Feel|Assume} about a {little|small|tiny|minor} {child|kid|youngster|little one} {trying|attempting|making an attempt|hoping} to {walk|stroll} {around|about|close to|all around} {wearing|sporting|putting on} a diaper! {Everyone|Everybody|Every person|Absolutely everyone} thinks the {baby|child|infant|little one} {looks|appears|seems|seems to be} so adorable, {right|correct|proper|appropriate}? A newborn {baby|child|infant|little one} or a {child|kid|youngster|little one} are in {need|require|want|need to have} of {attention|focus|interest|consideration}, {especially|particularly|specifically|specially} when it {comes|arrives|will come|happens} to the potty {training|coaching|instruction|teaching}. Their diaper {should|ought to|must|really should} be {comfortable|comfy|at ease|cozy} and that is what all {parents|mother and father|mothers and fathers|dad and mom} {strive|try} to {achieve|accomplish|attain|obtain}. {Such|This kind of|This sort of|These} cotton or other {organic|natural|natural and organic|organic and natural} {clothing|clothes|apparel|garments} absorbs {water|h2o|drinking water} and moisture {quickly|rapidly|swiftly|speedily} and {makes|tends to make|helps make|can make} the {child|kid|youngster|little one} {feel|really feel|experience|come to feel} {beautiful|stunning|gorgeous|lovely} and {comfortable|comfy|at ease|cozy}.

            Diapers are {usually|generally|typically|normally} {constructed|built|made|produced} of {100|one hundred|a hundred} percent pure cotton. {Whatever|What ever|No matter what|Whichever} the {type|kind|sort|form} of {fabric|material|cloth} you diaper is {made|produced|created|manufactured} of, it {must|should|need to|ought to} stand the {test|check|examination} of a {steady|constant|regular|continual} and {consistent|constant|steady|regular} staining, washing, drying, and bleaching. It {should|ought to|must|really should} have a {high|substantial|higher|large} absorbency {rate|price|charge|fee} but at the {same|exact same|identical|very same} time be {soft|gentle|comfortable|delicate} on {each|every|each and every|every single} child's delicate skin.";

            $SpunArticle = myTruncate(Spin($Article1),600);
            echo $Article . $SpunArticle;

            Hope this is more helpful...

              @ uhhhh.... I don't know if you noticed the date but this post is from 2008.

              I really hope they're not still hung up on this script.

                I did notice, which is why I mentioned that I was sorry I was a bit late, but with the other items I gave, I was thinking that it would be a benefit to others that are just now having the same problem as I did.

                  well.... IMHO that is silly...3 years...... either way bpats example is good.

                  one thing though. be sure to use the PHP tags when posting.

                  they could have

                  echo strip_tags($text, '<img><table>');
                  

                    Next time I will...

                      Write a Reply...