Pavel K
Pavel K

Reputation: 235

PHP preg_replace - remove BR tags between ul, li tags

I would like to create a regex which will be strip all BR tags between ul/ol li tags. For example:

Test<br>
<ul>
<li>
Test<br>
</li>
</ul>

And I want to get this result:

Test<br>
<ul>
<li>
Test
</li>
</ul>

I tried using this code:

    $param_array['description'] = preg_replace('/(?<=<ul>|<\/li>)([\s*<br>\s*|\s*<br\/>\s*|\s*<br \/>\s*]+)(?=<\/ul>|<li>)/is', "$1$3", $param_array['description']);
    $param_array['description'] = preg_replace('/(?<=<ol>|<\/li>)([\s*<br>\s*|\s*<br\/>\s*|\s*<br \/>\s*]+)(?=<\/ol>|<li>)/is', "$1$3", $param_array['description']);

but it doesn't work. Anyone can help me?

Upvotes: 2

Views: 1109

Answers (3)

Michael Duncan
Michael Duncan

Reputation: 11

$html = preg_replace_callback(
                        '~<ul>.*?</ul>~s', //match between <ul>s
                        function ($matches) {
                            return preg_replace('~<br.*?>~', '', $matches[0]); //strip all  <br>
                        },
                        $html 
                );

So the preg replace call back grabs everything between the ul tags and then passes it to the preg replace which strips the br tags

sorry for the late answer but I was trying to do the same thing and came across this.

Upvotes: 1

supernaut
supernaut

Reputation: 311

How about simply using CSS: li br {display:none;}

Upvotes: 1

Andrew1996
Andrew1996

Reputation: 436

Use the str_replace() function to remove any instances of
:)

<?php 
    $html = "Test<br>
    <ul>
    <li>
    Test<br>
    </li>
    </ul>";

    $without_breaks = str_replace(array('<br>', '&', '"'), ' ', $html);

?>

Upvotes: 2

Related Questions