在我的应用程序中,人们发布评论,有时用户不会关闭标签,因此会破坏我的所有布局。
我允许用户发布html评论。
例如,他们以这种方式发布:
<center><b>Hello
所以我想要的是关闭它上面的标签并以这种方式实现:
<center><b>Hello</b></center>
我在谷歌搜索但是没有找到一个好的解决方案,所以我在这里。
我尝试过这种方法,但它不起作用。
$yourText = $row['content'];
$doc = new DOMDocument();
$doc->loadHTML("$yourText");
$yourText = $doc->saveHTML();
感谢。
答案 0 :(得分:1)
您可能正在寻找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;
?>
答案 1 :(得分:1)
您可以使用此功能关闭内容中所有已打开的HTML标记:
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;
}
请致电:
$content = closeHtmlTags($content);
这将返回所有HTML标签关闭的内容。
您也可以使用PHP扩展程序php_tidy
$tidy = new Tidy();
$content = $tidy->repairString($str, array(
'output-xml' => true,
'input-xml' => true
));
希望这有帮助
答案 2 :(得分:0)
不允许用户发布HTML!他们可以修改您的网站,添加Javascript,做任何他们想做的事情。
确保使用strip_tags()
答案 3 :(得分:0)
您可以搜索打开的标签数量,然后搜索结束标签的数量并确保数字匹配 - 如果它不提交并让用户知道。
答案 4 :(得分:0)
最简单,最愚蠢的方式是:
$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);
}
但你最终可能会注射一些严重的XXS !!!