How to Regex-replace multiple <br /> tags with one <br /> tag?

$html = preg_replace('#(<br */?>\s*)+#i', '<br />', $html);

This will catch any combination of <br>, <br/>, or <br /> with any amount or type of whitespace between them and replace them with a single <br />.


You could use s/(<br \/>)+/<br \/>/, but if you are trying to use regex on HTML you are likely doing something wrong.

Edit: A slightly more robust pattern you could use if you have mixed breaks:

/(<br\ ?\/?>)+/

This will catch <br/> and <br> as well, which might be useful in certain cases.

Tags:

Php

Regex