1

I have a simple textarea where users can input a description for their product on my dummy system. I'm only allowing <b> <u> and <i> tags, without any attributes using the following code:

$description = strip_tags($_POST['description'], "<b><u><i>");
$description = preg_replace("/<([a-z][a-z0-9]*)[^>]*?(\/?)>/i",'<$1$2>', $description);

My problem is when a tag is left without it's closing part, for example:

<b>This is a <i>Test

The <b> and <i> tags will apply to everything that comes after this part. Is there any reliable way to automatically close the tags?

What I want is for the tag to be closed on the end of the user input, but only if it was left open.

Antonio Neto
  • 176
  • 10

2 Answers2

0

This code would require some additional finetuning but it will help you to get the gist of the idea.

$tags = ['b', 'i', 'u'];

foreach($tags as $t){
  if($a = substr_count($message, "<$t>") != $b = substr_count($message, "</$t>"){
    if($a > $b){
      $message .= str_repeat("<$t>", $a - $b);
    } else {
      // more closing tags then opening.
      $message = strrev($message);
      str_replace("<$t/>", '', $message, $b - $a);
      $message = strrev($message);
    }
  }
}

$message holds the entire text area text. It counts all the tags and if there is an inconsistency it will append at the end of the string.

Xorifelse
  • 7,878
  • 1
  • 27
  • 38
0

I ended up solving the problem by using Tidy. Here's the code:

$tidy = new Tidy();
$description = $tidy->repairString($description, array(
    'output-xml' => true,
    'input-xml' => true,
    'vertical-space' => false
));
Antonio Neto
  • 176
  • 10