如何从段落外删除分隔标签

问题描述:

我想要移除<p></p>以外的所有<br>标签。但是<p></p>内部的休息不应该受到伤害。我如何在PHP中实现这一点。下面是一个例子。如何从段落外删除分隔标签

$html = "<br> <p> This is the Firs para <br> 
     This is a line after the first break <br> 
     This is the line after the 2nd break <br> 
     Here the first para ends </p> 
     <br> 
     <br> 
     <p> This is the 2nd para <br> 
     This is a line after the first break in 2nd para <br> 
     This is the line after the 2nd break <br> 
     Here the 2nd para ends </p>" 

我想要的结果可考虑如下

$html = "<p> This is the Firs para <br> 
     This is a line after the first break <br> 
     This is the line after the 2nd break <br> 
     Here the first para ends </p> 
     <p> This is the 2nd para <br> 
     This is a line after the first break in 2nd para <br> 
     This is the line after the 2nd break <br> 
     Here the 2nd para ends </p>" 

这将帮助你。

$out = preg_replace("(<p(?:\s+\w+(?:=\w+|\"[^\"]+\"|'[^']+')?)*>.*?</p>(*SKIP)(*FAIL)" 
."|<br>)is", "", $html); 

echo $out; 
+0

虽然我不得不做一个小小的改变,但这工作。我必须在正则表达式中放入单引号,并删除所有双引号。谢谢@Arturs – Jeeva

下面

的解决方案可能是它可以帮助你。

$html = ""; 
$html .="<p><br>This is the Firs para <br> 
     This is a line after the first break <br> 
     This is the line after the 2nd break <br> 
     Here the first para ends </p>"; 

     $html .= "<p><br> This is the 2nd para <br> 
     This is a line after the first break in 2nd para <br> 
     This is the line after the 2nd break <br> 
     Here the 2nd para ends </p>"; 

echo $html; 

<?php 
$text = '<br> <p> This is the Firs para <br> 
     This is a line after the first break <br> 
     This is the line after the 2nd break <br> 
     Here the first para ends </p> 
     <br> 
     <br> 
     <p> This is the 2nd para <br> 
     This is a line after the first break in 2nd para <br> 
     This is the line after the 2nd break <br> 
     Here the 2nd para ends </p>'; 

$pattern = '/(<br>[\s\r\n]*<p>|<\/p>[\s\r\n]*<br>)/'; 
$replacewith = '<p>'; 
echo preg_replace($pattern, $replacewith, $text);