如何从段落外部删除break标记

时间:2017-08-08 12:29:03

标签: php html

我想删除<br>之外的所有<p></p>代码。但是<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>"

3 个答案:

答案 0 :(得分:4)

这会对你有帮助。

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

echo $out;

答案 1 :(得分:1)

<?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);

答案 2 :(得分:0)

以下是解决方案可能对您有帮助。

$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;