tags:

views:

2291

answers:

8

Wanted to convert

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

into

<br/>
+3  A: 

Use a regular expression to match <br/> one or more times, then use preg_replace (or similar) to replace with <br/> such as levik's reply.

mdec
+15  A: 

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.

levik
Does it ignore whitespace between the <br/>?
Sam
this allows for any whitespace chars (space, tab, newline) between <br/>
enobrev
@Sam: the \s means 'any whitespace character'.
sixlettervariables
@levik: you should change it to /(<br\s*\/?>\s*)+/ for a more robust/general matching of HTML/SGML/XHTML br's.
sixlettervariables
Done. Thanks for the advice.
levik
@levik: shouldn't the replace string be "<br />"? Your code currently outputs <br\/> to the HTML.
Wally Lawless
Good catch, @Power-coder. Thanks.
levik
@levik isn't it legal to have <br / >? Wouldn't you want that to be replaced? I'd add \s after your optional closing slash, but before your closing '>"
Jeff
A: 

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 );
Adam N
+7  A: 

Mine is almost exactly the same as levik's (+1), just accounting for some different br formatting:

preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput);
enobrev
Slightly better than levik's, and should even be faster.
Konrad Rudolph
+1  A: 

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 />'
michal kralik
+1: Regex seems better but this is a different approach.
JCasso
+2  A: 

Enhanced readability, shorter, produces correct output regardless of attributes:

preg_replace('{(<br[^>]*>\s*)+}', '<br/>', $input);
jakemcgraw
+1  A: 

Thanks all.. Used Jakemcgraw's (+1) version

Just added the case insensative option..

{(<br[^>]*>\s*)+}i

Great tool to test those Regular expressions is:

http://www.spaweditor.com/scripts/regex/index.php

AndrewC
Here's another tool for testing regular expressions: http://gskinner.com/RegExr/
Emanuil
A: 

A fast, non regular-expression approach:

while(strstr($input, "<br/><br/>"))
{
    $input = str_replace("<br/><br/>", "<br/>", $input);
}
Emanuil