tags:

views:

76

answers:

4

I want to replace all line break (<br> or <br />) in a string with PHP. What regular expression I should have to do this, using preg_replace?

Thanks!

A: 

Edit:

$string = str_replace(array('<br>','<br />'),'', $string);

Oh, regex isn't ideal tool for everything

So if you decide that insisting on using preg_replace isn't meaningful anymore, you can use this

Adam Kiss
I said using preg_replace, please :-)
User112312
I believe OP wishes to replace all `<br>` AND `<br />` instances.
jensgram
@jensgram - overlooked that, ty for hu.
Adam Kiss
+3  A: 

Replace |<br\s*/?>|i with "a string".

(Note that you can't parse HTML with regex even just for <br /> — e.g. what if this <br /> is part of a string in some inline Javascript? Use a parser to get reliable result.)

KennyTM
+2  A: 
/<br[^>]*>/

Should do ... and handles <br clear="all"> too. (If this is not a requirement, use KennyTM's solution instead. In all cases you should read his disclaimer.)

jensgram
<br data-synthesize="<br>" />
Williham Totland
@Williham Totland, not that, no :S
jensgram
Using possessive quantifiers: `/<br[^>]*+>/`
Geert
@Geert: <br data-synthesize="<br>" data-xml="<break />" />Really, I can play this game all day. ;D
Williham Totland
@Williham: sure, you are right, but that's a problem in jensgram's version too. All I wanted to say is that if a character group (`[^>]`) can't consume the character following it (`>`), you should use possessive quantifiers to prevent possible needless backtracking.
Geert
A: 

check this if it helps please post back if here is any problem.

$str = 'This is a test string<br>.and another string <br>that will replace<br> with <br />';

$pattern = "/<br>/";
$replace = "<br />";
echo preg_replace($pattern, $replace, $str);
Taha