0

I'm trying to write a regex that will match a given pattern between 2 and unlimited times. Effectively I'm just trying to combine multiple line breaks in to one, if any exist at all.

Sample input:

<br><br>
<br>
ABC
<br>
<br>

Expected output:

<br>
ABC
<br>

If the regex was run on the above output then I would expect to see the exact same output.

There could be any amount of whitespace between the <br> tags.

What I've tried:

$html = preg_replace('/(?:<br>\s?){2,}/s', null, $html);
1
  • If you don't have to bother with Windows-created files (with line terminator \r\n), consider replacing matches of /\n{2,}/ with \n or /\n(?=\n)/ with an empty string (both with the multiline flag set) . Commented Jun 20, 2020 at 21:49

1 Answer 1

1

Just look for a <br> followed by optional space characters 2 or more times and replace with <br>:

$html = preg_replace('/(<br>\s*){2,}/', '<br>', $html);

You might replace with "<br>\n" if you want.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.