我有一个div id喜欢从输出中删除看起来像
<div id="ithis" class="cthis">Content here which includes other elements etc..) </div>
Run Code Online (Sandbox Code Playgroud)
如何使用PHP和正则表达式删除此div及其中的所有内容?
谢谢.
cle*_*tus 13
简单的答案是你没有.您可以使用PHP的许多HTML解析器之一.正则表达式是一种操作HTML的片状且容易出错的方式.
话虽这么说你可以这样做:
$html = preg_replace('!<div\s+id="ithis"\s+class="cthis">.*?</div>!is', '', $html);
Run Code Online (Sandbox Code Playgroud)
但很多事情都可能出错.例如,如果包含div:
<div id="ithis" class="cthis">Content here which <div>includes</div> other elements etc..) </div>
Run Code Online (Sandbox Code Playgroud)
你会最终得到:
other elements etc..) </div>
Run Code Online (Sandbox Code Playgroud)
因为正则表达式将在第一个停止</div>.并且没有什么可以真正解决这个问题(使用正则表达式).
用解析器完成它看起来更像是这样的:
$doc = new DOMDocument();
$doc->loadHTML($html);
$element = $doc->getElementById('ithis');
$element->parentNode->removeChild($element);
$html = $doc->saveHTML();
Run Code Online (Sandbox Code Playgroud)