Tome A Tome A - 2 months ago 9
PHP Question

PHP Regex Remove leading and trailing <br /> within <p> tags

I can't figure this out for the life of me.

I need a regex expression that will strip out any leading or trailing

<br>
tags within
<p>
tags.

For example.

<p>
<br />Some test text. <br /> Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. <br /><br /><br />
</p>


Should become...

<p>Some test text. <br /> Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text. Some test text.</p>


I feel as though this should be very simple but I've hit a road-block. Any help would be greatly appreciated.

Answer

You just need a look-ahead and look-behind for <p> and </p>, and a non-capturing group for 1 or more occurrences of some variation of <br>.

For matching leading <br/> tags:

(?<=<p>)(?:\s*<br\s*\/?>)+\s*

For matching trailing <br/> tags:

(?:\s*<br\s*\/?>)+\s*(?=<\/p>)

Both together:

(?<=<p>)(?:\s*<br\s*\/?>)+\s*|(?:\s*<br\s*\/?>)+\s*(?=<\/p>)

Regex101 Demo