0

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!

  • Please don't use regexps to parse or modify HTML. The `
    ` cannot hold it is too late. http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags
    – Andrew Grimm Apr 07 '10 at 06:13

4 Answers4

3

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
  • 510,854
  • 105
  • 1,084
  • 1,005
2
/<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.)

Community
  • 1
  • 1
jensgram
  • 31,109
  • 6
  • 81
  • 98
0

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
  • 11,811
  • 9
  • 48
  • 81
0

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
  • 185
  • 2
  • 12