Need to keep return \\r

This is both PHP and MySQL related.

I am writing a blog type script and want to keep the return (enter key) so new paragraphs will start on a different line and lines can be separated. Currently if someone enters:

Line 1
Line 2

It will store and retrieve without separation as:

Line 1 Line 2

I thought addslashes() was what I needed but that is not working. The data is stored in the MySQL data field as text and I have magic_quotes_gpc turned on if that matters.

Turn it off. Don’t know if it will resolve your problem, but turn it off anyway :smiley:

And could you post some code please?

you could use the native nl2br() function or here is mine:


function nl2p($pee,  $skip=null) {

    if($skip) {
        return $pee;
    } else {
       // remove any carriage returns (mysql)
        $string = str_replace("\\r", '', $pee);
    
        // replace any newlines that aren't preceded by a > with a <br />
        $string = preg_replace('/(?<!>)\
/', "<br />\
", $string);
    
        return $string;
    }

}

nl2br() did the trick. I simply added this line after retreiving and just before printing the record:

$row[‘message’] = nl2br($row[‘message’]);

Problem solved.
Thanks!
Samantha

Off Topic:

lol @Spike, $pee?

That’ll work fine but tends to make a mess of HTML source code. The function I gave you makes slightly less mess and keeps tags tidy in your source.

:smiley: Well you know what its like when you get bored!


 function nl2p($pee,  $skip=null) {
    if($skip) {
       return $pee;
    }..

have any snow around to write in

Turn Magic Quotes off now. Turn Register Globals off now.

It is very likely at this point that the PHP team will follow through with the deprecation of these features and REMOVE them starting with version 5.4. (6.0 has been pushed off indefinitely).

So if you still write code requiring them that code will FAIL when 5.4 comes out.

spikeZ, I am interested in learning how to use the function you provided. How would I call this function?

Hi Samantha

Using the function is the same principle as using nl2br().


function nl2p($pee,  $skip=null) {

    if($skip) {
        return $pee;
    } else {
       // remove any carriage returns (mysql)
        $string = str_replace("\\r", '', $pee);
    
        // replace any newlines that aren't preceded by a > with a <br />
        $string = preg_replace('/(?<!>)\
/', "<br />\
", $string);
    
        return $string;
    }

} 

// to make it add the line breaks
$row['message'] = nl2p($row['message']);

The only reason I had the $pee skip part was because I had it as part of a CMS that served different data types that might not have needed line breaks

OK. For some reason I was thinking that I thought the variables used withing the function had to be used or declared outside of it.

Thanks.