PHP删除所有html标签并使用DOM Parser保留纯文本

时间:2017-08-01 12:26:51

标签: php html dom yii2

我正在尝试找到从字符串中删除所有html标记以保留纯文本的最佳方法。现在最简单的方法是strip_tags,但它不是最优的,因为它不能很好地处理破碎的标签等。我认为我需要的是一个DOM解析器。但是我不知道这件事是如何起作用的。

例如我有一个简单的字符串:

    <p>
        <strong>​
            Some plain text
        </strong>
    </p>

我想用DOM解析器去除所有标签并保留纯文本:

Some plain text

我该怎么做?我尝试使用removeChild但它删除了所有文本:

$dom = new DOMDocument();
$dom->loadHTML($translation->text);

foreach ($dom->getElementsByTagName("*") as $tag) {
    $tag->parentNode->removeChild($tag);
};

3 个答案:

答案 0 :(得分:0)

请试试这个:

<?php

$content = <<<EOM
  <p>
    <strong>
      Some plain text
    </strong>
  </p>
EOM;


$dom = new DOMDocument();
$dom->loadHTML($content);

echo trim($dom->textContent);

或者,简单地说,使用strip_tags即可。

<?php

$content = <<<EOM
  <p>
    <strong>
      Some plain text
    </strong>
  </p>
EOM;

echo trim(strip_tags($content));

答案 1 :(得分:0)

轻松快捷地使用此功能:

function fetch_string($content) {
    $content = preg_replace('@<script[^>]*?>.*?</script>@si', '', $content);
    $content = preg_replace('@<style[^>]*?>.*?</style>@si', '', $content);
    $content = strip_tags($content);
    $content = trim($content);
    return $content;
} 

用法:

$string = '<p><strong>​Some plain text</strong></p>';
$output = fetch_string($string);

答案 2 :(得分:0)

您可以使用HtmlPurifier。尝试:

echo yii\helpers\HtmlPurifier::process($html);

有关详细信息,请查看此link

相关问题