Preg匹配多个br标签

I have a textarea that users enter comments into and i am using nl2br to allow them to add spaces between blocks of text. I would like to replace occurrences where 3 or more br tags appear in a row and replace it with them all with a single tag.

one or two br tags don't get replaced they're fine but anymore more needs to be replaced with a single tag.

This is the regular expression i have so far

$comment = preg_replace('/(<br \/>){3,}/', '<br />', $comment);

$comment variable is

one<br />
<br />
<br />
<br />
<br />
two<br />
<br />
<br />
<br />
<br />
three<br />
<br />
four

Changing the regex to

$comment = preg_replace('/(<br \/>)/', '-', $comment);

replaces all the br tags with hyphens, so it seems like it's something to do with {3,} but i'm not sure.

You can use the following regular expression. Since the repeating tags could be on the same line or separated by a newline sequence, you need to account for whitespace.

$comment = preg_replace('~(?:<br />\s*){3,}~', '<br />', $comment);

Regex Explanation | Code Demo

If for some logical reason it removes certain whitespace you want retained, I would use ...

$comment = preg_replace('~(?:<br />\R?){3,}~', '<br />', $comment);

You could try the below regex also,

(?:<br \/>
?){3,}

DEMO

By adding an optional at the last will match also a newline character if presents.