Search code examples
phpregexline-breaks

php replace multiple br-tags


I have a string like the one below with multiple br-tags that can occur after \r\n or after multiple spaces. I'd like to find out when there are 3x br-tags or more right after another (no matter how many \r\n or spaces in between) and replace them for only 2x br-tags. <br> <br> <br> High Quality Print<br> <br><br> <br><br> <br> Data<br> <br> <br> <br>

Expected output:
<br><br>High Quality Print<br><br>Data<br><br>

I tried with str_replace but because of various spaces etc. that didn't work and I cannot do regex myself.


Solution

  • You can use this regex:

    $result = preg_replace('/(?:\s*<br[^>]*>\s*){3,}/s', "<br><br>", $input);
    //=> <br><br>High Quality Print<br><br>Data<br><br>
    

    RegEx Demo