Wanted to convert
into
You can do this with a regular expression:
preg_replace("/(<br\s*\/?>\s*)+/", "<br/>", $input);
This if you pass in your source HTML, this will return a string with a single <br/> replacing every run of them.
A fast, non regular-expression approach:
while(strstr($input, "<br/><br/>"))
{
$input = str_replace("<br/><br/>", "<br/>", $input);
}
without preg_replace, but works only in PHP 5.0.0+
$a = '<br /><br /><br /><br /><br />';
while(($a = str_ireplace('<br /><br />', '<br />', $a, $count)) && $count > 0)
{}
// $a becomes '<br />'
User may enter many variants
<br>
<br/>
< br />
<br >
<BR>
<BR>< br>
...and more.
So I think it will be better next
$str = preg_replace('/(<[^>]*?br[^>]*?>\s*){2,}/i', '<br>', $str);
You probably want to use a Regular Expression. I haven't tested the following, but I believe it's right.
$text = preg_replace( "/(<br\s?\/?>)+/i","<br />", $text );
Mine is almost exactly the same as levik's (+1), just accounting for some different br formatting:
preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput);