Question

So in a webpage i'm working on a user inputs a description that is html formatted and its added to the database which is working, the problem arises when I pull in the description and shorten it to 150 characters and add the "..." its messing up my html because sometimes tags go unclosed. Any suggestion would be wonderful

Was it helpful?

Solution

Here is a great answer to a similar question. You'll have to count tags and add whichever ones are truncated.

pseudo code

userData = getUserInput();
stack = array();
loop (line in userData) {
   matches = search for "<*>"; // may have multiple on one line
   loop (match in matches) {
      tagName = getTagNameFrom(match);
      if ("/" is not found) {
         push tagName on stack;
      } else if ("/" is found) {
         pop tagName off stack; 
         // There was an error if the stack is
         // empty or the tagName that was popped was not
         // the same.
      }
   }
}
foreach tagName in stack {
   userdata += "</" + tagName + ">";
}

By the way, your webpage sounds really vulnerable to XSS.

OTHER TIPS

  1. You can use some combination of strip_tags and splitting on different tags to get just pieces of things to shorten to 150 characters.

  2. You can use css styling called ellipsis. An example:

:

.ellipsisClass {
  width: 250px; // you MUST set a width
  white-space: nowrap;  // you MUST set nowrap
  overflow: hidden;  // you MUST set overflow to hidden
  text-overflow: ellipsis; // and then you can use text-overflow: ellipsis
}

you could refer the solution at the link: https://github.com/dhngoc/php-cut-html-string. If you want to add "..." at end of string after cutting. You have to adjust the function cutHtmlString, see these line codes:

$opened_tags = array_reverse($opened_tags);
foreach ($opened_tags as $key => $item) {
   $act_str = $act_str . '</'.$item.'>';    
}

Change to

$opened_tags = array_reverse($opened_tags);
foreach ($opened_tags as $key => $item) {
    if ($key == 0) {
     $act_str = $act_str . '...</'.$item.'>';      
   } else {
     $act_str = $act_str . '</'.$item.'>';    
   }       

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top