【问题标题】:How to remove HTML tags as well as HTML content within a string in PHP?如何在 PHP 中删除字符串中的 HTML 标签和 HTML 内容?
【发布时间】:2021-10-28 19:44:25
【问题描述】:

我有一个 .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 . I am a !

我怎样才能做到这一点?

【问题讨论】:

  • 你的字符串是来自传递给blade.php的变量吗?如果是,则在大括号中显示字符串,后跟感叹号{!! $string !!}
  • 其实字符串在一个.txt文件里面。
  • 在问题中添加如何显示 .txt 内容的代码,这将使用户更容易回答您的查询
  • 添加了我如何读取 .txt 文件的代码
  • @TejasS 正则表达式怎么样 /(]+)>).*?()/

标签: php html laravel string


【解决方案1】:

实现此目的的一种方法是使用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 会自动为无效的非结束标签添加一个结束标签。

【讨论】:

  • 成功了。谢谢!
猜你喜欢
  • 2015-07-07
  • 1970-01-01
  • 2013-02-24
  • 2022-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-09
相关资源
最近更新 更多