This is a problem in my journal script that I have been trying to solve for some time. I submit it to the Teeming Millions:
I have a form done in PHP into which I enter my journal entries and submit them to a MySQL database. When I type my entries, I have to use <br> and <p> for line breaks/new paragraphs. I have noticed that in many journal scripts, and on message boards, this isn’t necessary. For example, if I hit the enter twice key right now
there is a line break in the form where I am typing, and it will still be there when this post is displayed on the board.
There are several variations of regular expression replacement string functions such as preg_replace. Use one of them to replace newline characters with newline + <br>, like this:
That’s off the cuff, but I think the syntax is right.
You could either do this on input and save the HTML version in the db or do this on display. The former would be more efficient (only do the replace once). The latter would be more flexible, letting you change display without modifying old data.
What do $newstring and $oldstring represent? For instance, if the input field that I want to use this on is called “entry”, do I need to make those $newentry and $entry?
In my code line above, $oldstring is a variable holding the data you have now, either from the input form before writing to the database or after reading from the db before you display for the browser. Given the data in $oldstring, you want to replace all the newline characters with a newline character and an HTML break tag. The replace command will put its result in a new variable, which I called $newstring just for clarity. You could simply use the same variable both places, like
$entry = str_replace("
", "
<br>", $entry)
Whether you use the same variable or put the result of the replace command into a new variable like $newentry is a relatively minor concern.