Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert multiple <br/> tag to a single <br/> tag in php

Tags:

html

regex

php

Wanted to convert

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

into

<br/>
like image 680
Azrul Rahim Avatar asked Sep 25 '08 14:09

Azrul Rahim


4 Answers

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.

like image 180
levik Avatar answered Nov 12 '22 05:11

levik


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

preg_replace('/(<br[^>]*>\s*){2,}/', '<br/>', $sInput);
like image 17
enobrev Avatar answered Nov 12 '22 04:11

enobrev


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

preg_replace('{(<br[^>]*>\s*)+}', '<br/>', $input);
like image 6
Jake McGraw Avatar answered Nov 12 '22 03:11

Jake McGraw


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

like image 5
AndrewC Avatar answered Nov 12 '22 05:11

AndrewC