最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - JavaScript replace <br> with n - Stack Overflow

programmeradmin1浏览0评论

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.... 

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.... 
Share Improve this question edited Sep 17, 2012 at 14:58 Fenton 252k73 gold badges402 silver badges410 bronze badges asked Sep 17, 2012 at 14:52 Johnathan NixonJohnathan Nixon 231 silver badge3 bronze badges 4
  • Why can't you just reverse what you did when you added it? – andrewsi Commented Sep 17, 2012 at 14:53
  • 2 Why did you even alter text before storage? Why not modifying it only before display? – Paul Commented Sep 17, 2012 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 <br /> should be better done on print out. – VisioN Commented Sep 17, 2012 at 14:54
  • Has the data been stored as html characters as opposed to literals? I.e. Are < stored as &lt; ... If so use this: stackoverflow./a/5302086/94278 – Chris Commented Sep 17, 2012 at 14:57
Add a ment  | 

2 Answers 2

Reset to default 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");

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);
发布评论

评论列表(0)

  1. 暂无评论