2

I have just stored a paragraph of text in a MySQL database using JavaScript and PHP and replaced \n with <br />, the problem I'm now having is when I try and retrieve the text using PHP it prints it out as; <br />

Dear Sir/Maddam<br />This is a letter concerning the following;<br />I would like to.... 
Fenton
  • 241,084
  • 71
  • 387
  • 401
  • Why can't you just reverse what you did when you added it? – andrewsi Sep 17 '12 at 14:53
  • 2
    Why did you even alter text before storage? Why not modifying it only before display? – Paul Sep 17 '12 at 14:54
  • 3
    You should better store simple text without markup in the database. Web page is a view, so converting of `\n` to `
    ` should be better done on print out.
    – VisioN Sep 17 '12 at 14:54
  • Has the data been stored as html characters as opposed to literals? I.e. Are `<` stored as `<` ... If so use this: http://stackoverflow.com/a/5302086/94278 – Chris Sep 17 '12 at 14:57

2 Answers2

5

Well, the obvious solution is to just not replace \n with <br /> in the first place.

I don't know what language you're trying to reverse the damage in...

// PHP:
$out = preg_replace("/<br ?\/?>/i","\n",$in);

// JS:
out = input.replace(/<br ?\/?>/ig,"\n");
VisioN
  • 143,310
  • 32
  • 282
  • 281
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

If you want to simply remove those characters in your PHP you could use the handy strip_tags() function. This however will remove all HMTL elements in your string.

If you want to simply convert the <br/> string back to a \n then you can use php's str_replace() function.

$newString = str_replace("<br/>", "\n", $originalString);
Lix
  • 47,311
  • 12
  • 103
  • 131
  • It might be a typo, but in the OP's question `
    ` (with space) is used.
    – Jasper de Vries Sep 17 '12 at 14:59
  • @jas - That is just how I am used to writing `
    `. If the problem is that the OP can't just copy paste my code... then that is acceptable by me. I'm not writing code for anyone - I'm simply explaining what I would do.
    – Lix Sep 17 '12 at 15:03
  • 1
    Hehe. True. Anyhow, I would prefer this kind of replacement over using regular expressions. +1 – Jasper de Vries Sep 17 '12 at 15:05