Remove every <br /> except one per line?

Hello,

How can I turn this:

<br />

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

Into this:

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

Please notice the deletion of the first and last <br /> even if it’s mentioned once. In the middle we keep just one <br />

$lines = explode("\
", $str);
$newstr = [];
foreach ($lines as $line) {
  $line = trim($line);
  if ($line === '<br />') continue;
  $newstr[] = $line;
}
$newstr = implode("\
", $newstr);
if (strrchr($newstr, '<') === '<br />') {
  $newstr = substr($newstr, 0, strrpos($newstr, '<'));
}

This assumes the <br />s are all on different lines and are self-closing.


<?php

$string = '
<br />

...<br />
<br />
...<br />
...<br />
<br />
<br />
...<br />
';

preg_match_all('~\\.{3}~', $string, $matches);

echo implode(
  "<br />\
",
  array_shift($matches)
);

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

?>

*probably not what you’re looking for, but meets your spec. :stuck_out_tongue:

$str = '<br />

...<br />
<br />
...<br />
...<br />
<br />
<br />
...<br />';

$str = preg_replace('#<br\\s*/?>(\\s*<br\\s*/?>)+#is', '<br />', $str);
$str = preg_replace('#^\\s*<br\\s*/?>\\s*|\\s*<br\\s*/?>\\s*$#is', '', $str);

echo $str;

and also that they all have that space before the slash to ensure it works properly when served as HTML in Netscape 4.