如何用PHP preg_replace删除HTML表格中指定列?
解决方案
不要用字符串截取和正则处理HTML,这种方法脆弱易出错。建议用PHP的DOMDocument和DOMXPath解析操作表格,通过表头文本定位要删除的列,具体代码如下:
$html = file_get_contents('https://www.tradingview.com/markets/stocks-usa/market-movers-gainers/'); // 初始化DOM解析器 $dom = new DOMDocument(); // 忽略HTML解析错误 libxml_use_internal_errors(true); $dom->loadHTML($html); libxml_clear_errors(); $xpath = new DOMXPath($dom); // 定位目标表格 $table = $xpath->query('//table[contains(@class, "table-DR3mi0GH")]')->item(0); if (!$table) { die('未找到目标表格'); } // 要删除的列的表头文本 $columnsToRemove = ['Market cap', 'P/E(TTM)', 'EPS(TTM)', 'Employees']; // 获取表头行 $headerRow = $xpath->query('.//thead/tr', $table)->item(0); $headerCells = $xpath->query('.//th', $headerRow); // 记录要删除的列索引 $indicesToRemove = []; foreach ($headerCells as $index => $cell) { $text = trim($cell->textContent); if (in_array($text, $columnsToRemove)) { $indicesToRemove[] = $index; } } // 按倒序删除列(避免索引偏移问题) rsort($indicesToRemove); // 处理表头行,删除指定列 foreach ($indicesToRemove as $index) { if ($headerCells->item($index)) { $headerCells->item($index)->parentNode->removeChild($headerCells->item($index)); } } // 处理所有数据行,删除对应列 $rows = $xpath->query('.//tbody/tr', $table); foreach ($rows as $row) { $cells = $xpath->query('.//td', $row); foreach ($indicesToRemove as $index) { if ($cells->item($index)) { $cells->item($index)->parentNode->removeChild($cells->item($index)); } } } // 移除sup标签(用DOM方法更可靠) $supTags = $xpath->query('//sup[contains(@class, "tickerDescription-hMpTPJiS")]'); foreach ($supTags as $tag) { $tag->parentNode->removeChild($tag); } // 输出处理后的表格HTML echo $dom->saveHTML($table);
说明
- DOM解析器能可靠定位和操作HTML元素,规避正则、字符串截取的局限性。
- 通过表头文本确定删除列的索引,不受列class相同的影响。
- 倒序删除列是为了防止删除前列后,后续列的索引发生偏移。
内容的提问来源于stack exchange,提问作者bondikho
相关产品推荐
相关产品推荐

