Skip to content
Advertisement

(REGEX) Replace with empty when two appear in a string PHP

i have differents strings may be can:

1 Case

<br><br><br><br>{text}<br><br><br><br>{text}<br><br><br><br><br><br><br><br>{text}<br><br><br><br><br>Text<br><br><br><br><br>{text}<br><br><br>{text}<br><br><br><br><br><br>{text}";

2 Case

<br><br>{text}<br><br><br><br><br><br>{text}<br><br><br><br>{text}<br><br><br><br><br>Text<br><br>{text}<br><br><br>{text}<br><br><br><br>{text}<br><br>{text}";

3 Case

{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br><br><br>{text}<br><br><br><br>{text}<br><br><br><br><br>Text<br><br>{text}<br><br><br>{text}<br><br><br>{text}<br><br><br><br><br><br>Text";

I’m try to limit to

<br><br>

In cases if have found 3 or more continue

<br>

With the php code:

preg_replace("/<br>s+(?=<br>)/", "", $adContent);

Expected cases:

1 Case

<br><br>{text}<br><br>{text}<br><br>{text}<br><br>Text<br><br>{text}<br><br>{text}<br><br>{text}";

2 Case

<br><br>{text}<br><br>{text}<br><br>{text}<br><br>Text<br><br>{text}<br><br>{text}<br><br>{text}<br><br>{text}";

3 Case

{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br>Text<br><br>{text}<br><br>{text}<br><br>{text}<br><br>Text";

Used regex:

/<br>s+(?=<br>)/

Testing: https://paiza.io/projects/sLcZE5fW99p3gfrxaZGDsg

Thanks

My Regex not working

Advertisement

Answer

If you want to replace three or more <br> tags with just two tags, then use:

$input = "{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br><br><br>{text}<br><br><br><br>{text}<br><br><br><br><br>Text<br><br>{text}<br><br><br>{text}<br><br><br>{text}<br><br><br><br><br><br>Text";
$output = preg_replace("/(?:<br>){3,}/", "<br><br>", $input);
echo $output;

This prints:

{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br>{text}<br><br>Text<br><br>{text}<br><br>{text}<br><br>{text}<br><br>Text
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement