Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

php

I want <br /><br /> to turn into <br />

What's the pattern for this with regex?

Note: The <br /> tags can occur more than 2 times in a row.

like image 516
Weblurk Avatar asked Oct 12 '11 10:10

Weblurk


2 Answers

$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 />.

like image 66
FtDRbwLXw6 Avatar answered Oct 11 '22 12:10

FtDRbwLXw6


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.

like image 44
Williham Totland Avatar answered Oct 11 '22 11:10

Williham Totland