Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove every <br /> except one per line?

Tags:

regex

php

How can I turn this:


...<br />
<br />
...<br />
...<br />
<br />
<br />
...<br />

Into this using PHP:

...<br />
...<br />
...<br />
...

Please notice the deletion of the first and last
even if it's mentioned once. In the middle we keep just one

like image 287
Isamtron Avatar asked Jan 21 '26 01:01

Isamtron


2 Answers

preg_replace('#<br />(\s*<br />)+#', '<br />', $your_string);

This will replace instances of more than one <br />, optionally with whitespace separating them, with a single <br />.

Note that <br /> in the pattern matches exactly that. If you wanted to be more defensive, you could change it to <br[^>]*> which would allow for <br> tags that have attributes (ie. <br style="clear: both;" />) or that don't have the trailing slash.

like image 105
Daniel Vandersluis Avatar answered Jan 23 '26 13:01

Daniel Vandersluis


First of all, you should edit your question because the first <br /> doesn't appear.

Then to replace all duplicate <br /> AND the first and the last one, you can do :

$str = <<<EOD
<br />
...<br />
<br />
...<br />
...<br />
<br />
<br />
...<br />
EOD;

$str = preg_replace('~(^<br />\s*)|((?<=<br />)\s*<br />)|(<br />\s*$)~', '', $str);
echo "===\n",$str,"\n===\n";

This will output:

===
...<br />
...<br />
...<br />
...
===
like image 44
Toto Avatar answered Jan 23 '26 15:01

Toto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!