如何使用正则表达式删除特定标记

时间:2018-02-07 19:30:37

标签: php html regex

我试图在ul。

中删除ul标签和嵌套标签
<ul class="related">
<li><a href="/related-1.html" target="_blank">Related article</a></li>
<li><a href="/related-2.html" target="_blank">Related article 2</a></li>
</ul>

我刚刚使用这个删除了ul中的嵌套li(我使用php来处理这个东西,所以我从db中提取内容作为$ content)

$content = $rq['content'];  //here is the <ul class="related">... code
$content1 = preg_replace('~<ul[^>]*>\K(?:(?!<ul).)*(?=</ul>)~Uis', '', $content);   //it works here

到目前为止,我在$content1

中获得了下一个字符串
<ul class="related"></ul>

那么如何使用正则表达式删除这段剩余的代码呢?我尝试了类似的模式,但没有得到我想要的结果。

$finalcontent = preg_replace('~<ul[^>]*>\K.*(?=</ul>)~Uis', '', $content1);

1 个答案:

答案 0 :(得分:1)

以下内容可能适合您的目的:

$content1 = '<p>Foo</p><ul class="related"></ul><p>Bar</p>';
$finalcontent = preg_replace('~<ul[^>]*>.*</ul>~Uis', '', $content1);
echo $finalcontent;

preg_replace来电应从<ul...>...</ul>中删除所有$content1次出现。对于给定的示例内容,它返回:

<p>Foo</p><p>Bar</p>

如果您希望替换更具体,例如,为了仅删除<ul class="related">...</ul>而不是其他类型<ul>...</ul>的出现次数,您可以使正则表达式更具体。例如:

$content1 = '<p>Foo</p><ul class="related"></ul><p>Bar</p><ul><li>Do not delete this one</li></ul>';
$finalcontent = preg_replace('~<ul class="related">.*</ul>~Uis', '', $content1);
echo $finalcontent;

对于给定的示例,这将返回:

<p>Foo</p><p>Bar</p><ul><li>Do not delete this one</li></ul>