Kristian Rafteseth Kristian Rafteseth - 4 months ago 35
PHP Question

PHP: Remove excessive <br> tags

I got some "unclean" html string i need to clean up.

I want to replace "more than 2" html linebreaks in a row with 2 html linebreaks.

So the following string:

$string = 'ytefey soeije hesouhodeseojedowe<br><br>
<br>ioueshe oiwj<br /><br />oijeewje<br /><br> <br> <br>';

Should end up something like this:

$string = 'ytefey soeije hesouhodeseojedowe<br><br>
ioueshe oiwj<br /><br />oijeewje<br><br> ';

So far i got this:

$string = preg_replace('#(<br>|<br />){2,}#i', '<br><br>', $string);

But it doesnt take linebreaks and spaces into account.


You can use preg_replace() with a simple regex:

/(<br>\s*|<br \/>\s*){3,}/i

Basically it either matches <br> or <br />((<br>|<br \/>)) with zero or more spaces in front of them(\s*) at least 3 or more times({3,}).

$string = preg_replace("/(<br>\s*|<br \/>\s*){3,}/i", "<br><br>", $string);