繁体   English   中英

如何删除 HTML 标签以及 PHP 字符串中的 HTML 内容?

[英]How to remove HTML tags as well as HTML content within a string in PHP?

我有一个 .txt 文件。 使用以下代码我阅读了它:

while (!feof($handle)) {
            yield trim(utf8_encode(fgets($handle)));
        }

现在从检索到的字符串中,我不仅要删除 HTML 标签,还要删除里面的 HTML 内容。 找到了许多删除标签的解决方案,但不能同时删除 - 标签 + 内容。

示例字符串 - Hey my name is <b>John</b>. I am a <i>coder</i>! Hey my name is <b>John</b>. I am a <i>coder</i>!

必需的输出字符串 - Hey my name is . I am a ! Hey my name is . I am a !

我怎样才能做到这一点?

实现此目的的一种方法是使用DOMDocumentDOMXPath 我的解决方案假设提供的 HTML 字符串没有容器节点,或者容器节点的内容不会被剥离(因为这会导致一个完全空的字符串)。

$string = 'Hey my name is <b>John</b>. I am a <i>coder</i>!';

// create a DOMDocument (an XML/HTML parser)
$dom = new DOMDocument('1.0', 'UTF-8');
// load the HTML string without adding a <!DOCTYPE ...> and <html><body> tags
// and with error/warning reports turned off
// if loading fails, there's something seriously wrong with the HTML
if($dom->loadHTML($string, LIBXML_HTML_NODEFDTD | LIBXML_HTML_NOIMPLIED | LIBXML_NOERROR | LIBXML_NOWARNING)) {
  // create an DOMXPath instance for the loaded document
  $xpath = new DOMXPath($dom);

  // remember the root node; DOMDocument automatically adds a <p> container if one is not present
  $rootNode = $dom->documentElement;
  // fetch all descendant nodes (children and grandchildren, etc.) of the root node
  $childNodes = $xpath->query('//*', $rootNode);
  // with each of these decendants...
  foreach($childNodes as $childNode) {
    // ...remove them from their parent node
    $childNode->parentNode->removeChild($childNode);
  }

  // echo the sanitized HTML
  echo $rootNode->nodeValue . "\n";
}

如果您确实想要剥离潜在的容器代码,那么它会有点困难,因为很难区分原始容器节点和由DOMDocument自动添加的容器节点。


此外,如果发现了非预期的非结束标记,可能会导致意外结果,因为它将剥离所有内容,直到下一个结束标记,因为DOMDocument会自动为无效的非结束标记添加结束标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM