How to use nl2br and its reverse br2nl in php

I was having some weird trouble with my new line break  in my blog.

I used a <textarea> where I written the post content and
in the backend , used  nl2br() to store the post content variable , insert into the database.

This works as it should, the newlines (\n) have been converted to matching numbers of <br />
and the post shows the correct number of <br /> in the html when viewing the page.

but when i go to edit the post content into a <textarea>,i used

$post_content = str_replace(“<br />”,”\n”, $post_content);

and the result is, “an extra newline always find in it”

i was troubled, but after some sort of programming effort i solved this issue.

i tell you, how.

1. i used this,

$post_content  = str_replace(‘\n’,”<br />”,$post_content );

$post_content = str_replace(“\r\n”,”<br />”,$post_content );

in place of nl2br()

2. and then in edit section used as before,

$post_content  = str_replace(‘<br />’,”\n”,$post_content );

thats it the magic, and it works well now and all time

thanks for view this post, and also keep comment, its give me energy to write this kind of useful  blogs. satellite maps relevant domains .

4 thoughts on “How to use nl2br and its reverse br2nl in php

      1. site whois

        first of all ‘\n’ can’t work since regex must be escaped with double quotes e.g. “\n”.
        secondly, $post_content = str_replace(‘\n’,””,$post_content ); doesn’t delete the newlines you get working with mysql databases, for this you must delete the newlines as soon as you have changed them into html breaks.

        1. webadmin Post author

          yes ali,

          good caught,

          it must be “\n”.

          so the change is here..

          $post_content = str_replace(‘\n’,”<br />”,$post_content );

          this will be change into

          $post_content = str_replace(“\r\n”,”<br />”,$post_content );

          thats it.

          and it works well

          thanks for your precious comment.

Comments are closed.