【问题标题】:How to remove specific html tags with contents in php?如何删除包含 php 内容的特定 html 标签?
【发布时间】:2021-10-09 02:33:34
【问题描述】:

我有一些字符串格式的内容,包括一些不需要的 html 标记及其内容。我正在寻找一种删除它们的方法,但仍然找不到完美的解决方案。

方法一

通常,我们使用strip_tags 来删除标签,但它会保留标签内的文本内容。

方法二

然后我尝试使用preg_replace 来删除标签以及使用/<font[\s\S].*?<\/font>/ 等模式的内容


测试

但在实际情况中,标签有时会包含相同的标签,例如

text to keep <span xxx="xxxx"><span xxx="xxx">unwanted text</span> unwanted text </span> text to keep ...<some other tags>

使用这两种方法都不会得到想要的结果。

方法一输出

unwanted text unwanted text text to keep

方法二输出

unwanted text &lt;/span&gt; text to keep

存档的最佳方式是什么?

我正在寻找这样的解决方案(我知道这种模式不起作用):

$remove_arr = [
   'span',
   'div',
   'strong'
]
foreach($remove_arr as $remove){
  $content = preg_replace("/<$remove.*?<\/$remove>/", '',$content);
}

先谢谢各位了!

更新

代码位于名为 Collect.php 的文件中

<?php
namespace app\common\model;
use think\Db;
use think\Cache;
use app\common\util\Pinyin;
use think\Request;

class Collect extends Base {
   //the code
}

【问题讨论】:

    标签: php html regex


    【解决方案1】:

    strip_tags() 有其局限性,正则表达式并不是有效处理任意 HTML 字符串的工具(请参阅this question)

    您需要使用能够理解 HTML 的东西。即DOMDocument。你可以递归到树上找到你想要的节点,但幸运的是 PHP 有 DOMXPath 会为你做这件事

    这个sn-p会将一个字符串加载到DOMDocument中,搜索并删除所有&lt;span&gt;元素,并将剩余部分返回到一个字符串中:

    $str = <<<HTML
    <!doctype html>
    <html>
    <body>
    text to keep <span xxx="xxxx"><span xxx="xxx">unwanted text</span> unwanted text </span> text to keep
    </body>
    </html>
    HTML;
    $doc = new DOMDocument();
    $doc->loadHTML($str);
    $xpath = new DOMXPath($doc);
    
    foreach($xpath->evaluate("//span") as $node) {
        echo 'Removing: '.$node->nodeValue."<br>";
        $node->parentNode->removeChild($node);
    }
    $output = $doc->saveHTML();
    echo htmlspecialchars($output);
    

    输出:

    Removing: unwanted text unwanted text
    Removing: unwanted text
    <!DOCTYPE html> <html> <body> text to keep text to keep </body> </html> 
    

    演示:https://3v4l.org/6m0e2

    【讨论】:

    • 感谢您的回答。我真的认为这会有所帮助。但是,我在测试时遇到了一个问题。它显示Fatal error: Class 'app\common\model\DOMDocument' not found。我使用用 thinkphp 构建的自定义 CMS。我认为这可能是因为我没有使用正确的命名空间?还是我需要一些特定的 php 扩展才能使用 DOMDocument?我搜索一些文章。有人说需要php-xml,有人说需要php-dom。看来我启用了两个扩展。请指教。再次感谢您的回复。
    • DOMDocument 位于根命名空间中,因此您需要执行 $dom = new \DomDocument(); 或在类定义上方放置 use 语句
    • @philip 如果 PHP 抱怨找不到 DOMDocument,那么您需要在系统上安装它。我使用 Ubuntu,他们的软件包列表表明 DOMDocument 在 php-xml 和 php-dom 中。安装哪个无关紧要。对于所有与 Debian 相关的发行版都应该如此,但其他版本可能会以不同的方式打包它们的软件。
    • @Tangentially Perpendicular 谢谢你的回答。它解决了这个问题。很高兴我以前学过一些 xpath。现在有用了哈哈。 @DarkBee 谢谢你的解释。在 DomDocument() 之前添加 \;帮助。如果我想使用use。路径应该是什么?我的 php 文件夹在网站文件夹之外。
    • use DomDocument; 就足够了
    猜你喜欢
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多