我有一个 div id 想要从输出中删除
<div id="ithis" class="cthis">Content here which includes other elements etc..) </div>
如何使用 PHP 和正则表达式删除此 div 及其中的所有内容?
谢谢。
最佳答案
简单的答案是您不需要。您可以改用 PHP 的众多 HTML 解析器之一。正则表达式是一种不稳定且容易出错的 HTML 操作方式。
也就是说你可以这样做:
$html = preg_replace('!<div\s+id="ithis"\s+class="cthis">.*?</div>!is', '', $html);
但是很多事情都可能与此有关。例如,如果它包含一个 div:
<div id="ithis" class="cthis">Content here which <div>includes</div> other elements etc..) </div>
你最终会得到:
other elements etc..) </div>
因为正则表达式将在第一个 </div>
处停止.不,您真的无法始终如一地解决此问题(使用正则表达式)。
使用解析器完成后看起来更像这样:
$doc = new DOMDocument();
$doc->loadHTML($html);
$element = $doc->getElementById('ithis');
$element->parentNode->removeChild($element);
$html = $doc->saveHTML();
关于php - 如何使用 RegEx 删除 html 元素及其内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1114916/