Question

I have been scanning through posts here for a bit and while I found quite a bit of it useful, I was unable to find all of my questions. More or less I am coding a website with a back-end that allows the user (me) to post stories that are then saved to the MySQL DB (UTF-8) for later use. I then on the front-end have a page that displays said story with attempts to bring back in the P tags and BR tags to make the format look nice.

Upon saving the stories content I used an "escape" function to turn all HTML tags the user might enter into part of a string rather than a code. I have figured out a way, however sloppy it may be, to bring back

tags with the following function:

function set_pars($string) {
   return "<p>" . str_replace("\r\n", "</p><p>", $string) . "</p>";
}

Seeing as that there is no \n at the beginning of the string and no \r at the end (if I am even understanding these two characters correctly) I was forced to add them at the beginning and the end. I have yet to find a way to add in the BR for returned blank lines. I thought I was being brilliant for a brief moment when I set the P tag to "height: 20px;" until I had a paragraph that was longer than one line... I am sure someone might get a good laugh out of that one.

The reason I have chosen to do the styling after the fact, rather than adding them to the DB directly, is so I don't have to see the ugly tag mock-up while working with a story (though as I am writing this it has occurred to me I could remove them before filling the retrieved story into an TEXTAREA feild. Seems like unnecessary back and forth though.) What ever helps me to understand and make this work! Thank you in advanced for any info anyone can shed on this topic.

In case my ramblings have gone too far past the point I want to make this:

Hello I am the first line.

Hello I am the second line.

Look like this:

<p>Hello I am the first line.</p>
<br />
<p>Hello I am the second line.</p>

This is the final function I ended up using and it works perfectly:

function set_pars($string) {
$string = str_replace(array("\n\r","\n","\r"), array("<br />","<p>","</p>"), $string);
return "<p>" . $string . "</p>";

}

Was it helpful?

Solution

Replace the \r\n\r\n first with </p><br /><p> and then on the resulting string, do the \r\n replacement the way you are doing now.

When you hit enter twice to create a blank line in between the two, just the \r\n are repeated twice.

Hello I am the first line.

Hello I am the second line.

Above results in Hello I am the first line.\r\n\r\nHello I am the second line..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top