如果不完整,删除HTML实体


Remove HTML Entity if Incomplete

我有一个问题,我已经显示了从数据库中提取的字符串的400个字符,但是,这个字符串需要包含HTML实体。

偶然地,客户端创建了字符串,使第400个字符正好位于结束p标记的中间,从而杀死该标记,导致其后的代码出现其他错误。

我希望这个结束p标签完全被删除,因为我有一个"…"阅读更多"链接附在结尾,如果附在现有段落中,会看起来更干净。

覆盖所有HTML实体问题的最佳方法是什么?是否有一个PHP函数,将自动关闭/删除任何错误的HTML标签?我不需要一个明确的答案,只要一个方向就会很有帮助。

谢谢。

这里有一种简单的方法可以用DOMDocument实现,它不是完美的,但它可能会让你感兴趣:

<?php 
function html_tidy($src){
    libxml_use_internal_errors(true);
    $x = new DOMDocument;
    $x->loadHTML('<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />'.$src);
    $x->formatOutput = true;
    $ret = preg_replace('~<(?:!DOCTYPE|/?(?:html|body|head))[^>]*>'s*~i', '', $x->saveHTML());
    return trim(str_replace('<meta http-equiv="Content-Type" content="text/html;charset=utf-8">','',$ret));
}
$brokenHTML[] = "<p><span>This is some broken html</spa";
$brokenHTML[] = "<poken html</spa";
$brokenHTML[] = "<p><span>This is some broken html</spa</p>";
/*
<p><span>This is some broken html</span></p>
<poken html></poken>
<p><span>This is some broken html</span></p>
*/
foreach($brokenHTML as $test){
    echo html_tidy($test);
}
?> 

虽然注意到Mike 'Pomax' Kamermans的评论

为什么你不把段落或内容的最后一个词删除,如果这个词是完整的你删除它,如果不是完整的你也删除它,你确定内容仍然干净,我给你一个例子,代码将是什么样子:

while($row = $req->fetch(PDO::FETCH_OBJ){
  //extract 400 first characters from the content you need to show
  $extraction = substr($row->text, 0, 400);
  // find the last space in this extraction
  $last_space = strrpos($extraction, ' ');
  //take content from the first character to the last space and add (...)
  echo substr($extraction, 0, $last_space) . ' ...';
}

删除最后一个断开的标签,然后strip_tags

$str = "<p>this is how we do</p";
$str = substr($str, 0, strrpos($str, "<"));
$str = strip_tags($str);