You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP str_ireplace无法移除DOMDocument指定class的td标签如何解决

问题根源

原代码页面空白、功能失效是几个核心逻辑错误导致的:

  • str_ireplace是字符串处理函数,无法直接传入DOM节点对象做替换,传入后会因类型不匹配返回空值,直接导致输出空白
  • 全局获取所有td标签后嵌套遍历,会把不在目标infotec类表格内的td也纳入判断,范围逻辑错误
  • DOM节点集合(DOMNodeList)是实时更新的,如果遍历过程中直接修改/删除节点,会造成集合指针偏移,出现漏删、报错问题
修正后可直接运行的代码
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://website.ndd");

$tables = $doc->getElementsByTagName("table");
foreach ($tables as $table) {
    // 跳过不包含infotec类的表格
    if (stripos($table->getAttribute('class'), "infotec") === false) {
        continue;
    }
    // 仅获取当前目标表格下的td节点,不全局查找
    $tds = $table->getElementsByTagName("td");
    $removeList = [];
    // 先收集所有待删除的节点,避免遍历实时节点集时指针错乱
    foreach ($tds as $td) {
        if (stripos($td->getAttribute('class'), "navigation-only") !== false) {
            $removeList[] = $td;
        }
    }
    // 统一执行删除操作
    foreach ($removeList as $targetTd) {
        $targetTd->parentNode->removeChild($targetTd);
    }
    // 输出处理完成的表格内容
    echo $doc->saveHTML($table);
}
可选优化:精确匹配类名

如果要避免stripos误匹配navigation-only-suffix、testnavigation-only这类不符合要求的类名,可以用DOMXPath做更精准的节点查找,替换对应逻辑即可:

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile("https://website.ndd");
$xpath = new DOMXPath($doc);

// 直接查找所有位于infotec类表格下、带navigation-only类的td节点
$targetTds = $xpath->query('//table[contains(@class, "infotec")]//td[contains(@class, "navigation-only")]');
$removeList = [];
foreach ($targetTds as $td) {
    $removeList[] = $td;
}
foreach ($removeList as $td) {
    $td->parentNode->removeChild($td);
}

// 按需输出处理后的内容,比如输出整个页面:
// echo $doc->saveHTML();

内容的提问来源于stack exchange,提问作者user7962781

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 06:39:32