如何用php关闭评论中的标签

In my application people are posting comments, and some times the user doesn't close the tags so it destroys all my layout.

I allow user to post html comment.

For example they post this way :

<center><b>Hello

So what I want is to close the tags on it and make it this way:

<center><b>Hello</b></center>

I searched on Google but din't find a good solution so I am here.

I tried this method but it does not work.

$yourText = $row['content'];

$doc = new DOMDocument();
$doc->loadHTML("$yourText");
$yourText = $doc->saveHTML();

Thanks.

You can use this function to close all the opened HTML tags in your content :

function closeHtmlTags($html) {

    preg_match_all('#<(?!meta|img|br|hr|input\b)\b([a-z]+)(?: .*)?(?<![/|/ ])>#iU', $html, $result);
    $openedtags = $result[1];
    preg_match_all('#</([a-z]+)>#iU', $html, $result);
    $closedtags = $result[1];
    $len_opened = count($openedtags);

    if (count($closedtags) == $len_opened) {
        return $html;
    }
    $openedtags = array_reverse($openedtags);

    for ($i=0; $i < $len_opened; $i++) {
        if (!in_array($openedtags[$i], $closedtags)) {
            $html .= '</'.$openedtags[$i].'>';
        } else {
            unset($closedtags[array_search($openedtags[$i], $closedtags)]);
        }
    }

    return $html;
}

Just call :

$content = closeHtmlTags($content);

This will return the content will all HTML tags close.

Also you can use the PHP extension php_tidy

$tidy = new Tidy();
$content = $tidy->repairString($str, array(
    'output-xml' => true,
    'input-xml' => true
));

Hope this helps

Don't allow users to post HTML! They can modify your site, add Javascript, do anything they want.

Make sure to remove HTML formatting with strip_tags()

You're probably looking for HTML Tidy.

<?php
ob_start();
?>
<html>a html document</html>
<?php
$html = ob_get_clean();

// Specify configuration
$config = array(
           'indent'         => true,
           'output-xhtml'   => true,
           'wrap'           => 200);

// Tidy
$tidy = new tidy;
$tidy->parseString($html, $config, 'utf8');
$tidy->cleanRepair();

// Output
echo $tidy;
?>

You can search for the number of open tags, then search for the number of closing tags and making sure that number matches - if it doesn't don't submit and let the user know.

The easiest and dyrtiest way would be this:

$yourText = $row['content'];

$doc = new DOMDocument();
$doc->loadHTML("$yourText");
$otherText = $doc->saveHTML();

if(!empty($otherText)){
    //the usertext was good html
}else{
    $yourText = strip_tags($yourText);
}

but you might end up with some serious XXS injections!!!