PHP Regex - 删除标签之间的文本

Iva*_*ova 2 php regex

我有这个:

$text = 'text text text s html tagove
<div id="content">ss adsda sdsa </div>
oshte text s html tagove';
$content = preg_replace('/(<div\sid=\"content\">)[^<]+(<\/div>)/i', '', $text);
var_dump($content); 
Run Code Online (Sandbox Code Playgroud)

但如果<div id="content"></div>包含其他标签,例如<b><i>,则不起作用。

例如:

$text = 'text text text s html tagove
<div id="content"><b> stfu </b> ss adsda sdsa </div>
oshte text s html tagove';
Run Code Online (Sandbox Code Playgroud)

gho*_*oti 5

您可以改用惰性量词

$s="foo<div>Some content is <b>bold</b>.</div>bar\n";

print preg_replace("/<div>.+?<\/div>/i", "", $s);'
Run Code Online (Sandbox Code Playgroud)

输出:

foobar
Run Code Online (Sandbox Code Playgroud)

根据评论更新:

[ghoti@pc ~]$ cat doit.php 
<?php

$text = 'text text text s html tagove
<div id="content"><b> stfu </b> ss adsda sdsa </div>
oshte text s html tagove';

print preg_replace('/<div id="content">.+?<\/div>/im', '', $text) .  "\n";

[ghoti@pc ~]$ php doit.php 
text text text s html tagove

oshte text s html tagove
[ghoti@pc ~]$ 
Run Code Online (Sandbox Code Playgroud)