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
spaces. We can extend this regex to include that as well:
$html = preg_replace('#(<br *\/?>\s*( )*)+#', '<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>
精彩评论