开发者

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

开发者 https://www.devze.com 2023-04-12 05:53 出处:网络
I want <br /><br /> to turn into <br /> What\'s the pa开发者_C百科ttern for this with regex?

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

What's the pa开发者_C百科ttern for this with regex?

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


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


(<br />)+

Will match them so you could use preg_replace to replace them (remember to correctly escape characters).


The answer from @FtDRbwLXw6 is great although it does not account for &nbsp; spaces. We can extend this regex to include that as well:

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


This works fine. It works with all the combinations below.

$html = '<br><br>
Some text
<br>
<br>
Some another<br/><br>';

$html = preg_replace("/(<br.*?>\s*)+(\n)*+(<br.*?>)/","<br>",$html);

$html will be changed to

<br>
Some text
<br>
Some another<br>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号