正则去除一些DIV内的内容。
我想正则去除一些DIV的内容。div id 或者class 带comment或者share的(comment和share是一个模糊匹配。),比如<div id="comment">, <div class="header-comment">, <div id="comment-footer">等等。
下面这段测试代码,保留Main content.去除后面的评论部分。
$htmls = <<<EOT
<div id="content">
Main content.
</div>
<div id="comment">
<ul>
<li class="comment">
<div class="header-comment">
Comment:
<span class="date-comment">8/11/2012, 21:25</span>
</div>
<h4>Some Text</h4>
<p class="test-comment">Blah~~ Blah~~ Blah~~</p>
<div class="share">
<div class="vote">
<a class="vota yes" title="Like">2</a>
<a class="vota no" title="Unlike">0</a>
</div>
</div>
</li>
<li class="comment">
<div class="header-comment">
Comment:
<span class="date-comment">8/11/2012, 23:08</span>
</div>
<h4>Other Text</h4>
<p class="test-comment">Blah~~ Blah~~ Blah~~</p>
<div class="share">
<div class="vote">
<a class="vota yes" title="Like">4</a>
<a class="vota no" title="Unlike">0</a>
</div>
</div>
</li>
</ul>
</div>
EOT;
$htmls = preg_replace('/<div[^>]*(comment|share)[^>]*>(.*?)<\/div>/is', '', $htmls);
echo $htmls;
</div>
<div id="footer">
Footer content.
</div>
EOT;