Php 从HTML中删除具有特定类的范围,但不使用正则表达式删除内容

Php 从HTML中删除具有特定类的范围,但不使用正则表达式删除内容,php,regex,html-parsing,Php,Regex,Html Parsing,下面是示例html <div> <span class="target"> Remove parent span class only and save this text </span> </div> 仅删除父span类并保存此文本 这里我想上面的html如下使用正则表达式函数只 <div> Remove parent span class only and save this text </div>

下面是示例html

<div>
<span class="target"> Remove  parent span class only and save this text </span>      
</div>

仅删除父span类并保存此文本
这里我想上面的html如下使用正则表达式函数只

<div>
Remove parent span class only and save this text
</div>

仅删除父span类并保存此文本
我试过这个:

$html = preg_replace('#<h3 class="target>(.*?)</h3>#', '', $html);

$html=preg_replace('#我不太明白,但使用jquery,您可以尝试以下方法:

$('#target').parent().append($('#target').text());
$('#target').remove();

我不太明白,但使用jquery,您可以尝试以下方法:

$('#target').parent().append($('#target').text());
$('#target').remove();
试试这个:

$html = preg_replace('#<(\w+) class="target">(.*)<\/\1>#', '\2', $html);
$html=preg#u replace('#(.*)#','\2',$html);
说明:

(区分大小写)

第二个捕获组
(.*)
匹配任何字符

完全匹配

\2
表示它将替换为第二个捕获组

备注:将正则表达式与HTML一起使用可能会导致意外结果,如果使用它,请小心(例如,在这种情况下,可以通过向标记添加另一个类或属性来破坏正则表达式)。

尝试以下方法:

$html = preg_replace('#<(\w+) class="target">(.*)<\/\1>#', '\2', $html);
$html=preg#u replace('#(.*)#','\2',$html);
说明:

(区分大小写)

第二个捕获组
(.*)
匹配任何字符

完全匹配

\2
表示它将替换为第二个捕获组


PS:将正则表达式与HTML一起使用可能会导致意外的结果,如果您使用它,请小心(例如,在这种情况下,您可以通过向标记添加另一个类或属性来破坏正则表达式)。

您匹配了错误的标记,h3而不是span 还要检查preg_replace的签名,第二个参数是replacement,在您的例子中它是空字符串

$html = preg_replace('/<(span)[^\>]+>(.*?)<\/\1>/i', '\2', $html);
$html=preg_replace('/]+>(.*?/i','\2',$html);
编辑: 只是注意到op只想删除具有特定类的跨距

$html = preg_replace('/<(span).*?class="\s*(?:.*\s)?target(?:\s[^"]+)?\s*"[^\>]*>(.*)<\/\1>/i', '\2', $html);

$html=preg_replace('/您匹配了错误的标记,h3而不是span
还要检查preg_replace的签名,第二个参数是replacement,在您的例子中它是空字符串

$html = preg_replace('/<(span)[^\>]+>(.*?)<\/\1>/i', '\2', $html);
$html=preg_replace('/]+>(.*?/i','\2',$html);
编辑: 只是注意到op只想删除具有特定类的跨距

$html = preg_replace('/<(span).*?class="\s*(?:.*\s)?target(?:\s[^"]+)?\s*"[^\>]*>(.*)<\/\1>/i', '\2', $html);

$html=preg\u replace(“/你试过什么吗?$html=preg\u replace(“#^然后将此添加到你的问题中,并显示你的努力/工作!感谢你的快速回答,但没有成功。你试过什么吗?$html=preg\u replace(“#^然后把这个问题写进你的问题中,展示你的努力/工作!谢谢你的快速回答,但这不管用为什么OP“尝试这个”请说明你做了什么,以及你为什么这样做,不仅是为了OP,也是为了SO的未来访客。编辑:增加了精确性谢谢,你让我的一天过得很轻松。不客气。别忘了把这个问题标记为已解决;)OP为什么要“尝试这个”请解释一下你做了什么,以及你为什么这样做,不仅是为了OP,也是为了SO的未来访客。编辑:增加了精确性谢谢,你让我的一天过得很轻松。不客气。别忘了把这个问题标记为已解决;)但是OP想要一个使用正则表达式的解决方案。但是OP想要一个使用正则表达式的解决方案。