Page 1 of 1

Problem: replace \r\n when using echo

Posted: Tue Aug 16, 2011 7:51 pm
by DedMousie
I've got a form where I'm properly (hope it's proper!) escaping and trimming entries before entering to my database. The database inserting works properly with all variables clean and special characters escaped. However, I need to DISPLAY one of the form variables on a confirmation page. It's a multipage form, so the escaping and trimming have taken place a page or two before.


If I output my variable
echo $myvar;
gives me everything between the quotes here:
"There\'s a bunch of stuff and the percent is\r\n5% - another percent\r\n6%" .... and so forth

What can I use to simply display this as:
"There's a bunch of stuff and the percent is 5% - another percent 6%"

I tried a combination of stripslashes with a few other things, but it simply is not displaying correctly for me.

Be kind to the newbie...

Thanks

Re: Problem: replace \r\n when using echo

Posted: Tue Aug 16, 2011 9:38 pm
by yacahuma
one thing to remember is that you never output the text as is from user input. you alway use
htmlentities()

you can do something like this

Code: Select all

echo nl2br( htmlentities( $string ) );

Re: Problem: replace \r\n when using echo

Posted: Wed Aug 17, 2011 12:25 am
by DedMousie
yacahuma wrote: you can do something like this

Code: Select all

echo nl2br( htmlentities( $string ) );
Hmmm - no effect at all.
I'd tried nl2br previously, and it didn't do anything.

OK, the only thing I can think of, and it seems rather inefficient, is to query the database right after the insert and get the variables I wish to display from there.

Re: Problem: replace \r\n when using echo

Posted: Thu Aug 18, 2011 8:24 am
by yacahuma
you must have some other characters. If you try the code I gave you with a string like "helo\r\nworld" it will work as expected

Re: Problem: replace \r\n when using echo

Posted: Thu Aug 18, 2011 9:21 am
by Dorin85
This is assuming that you want to convert them to br

Code: Select all

$str     = "There\'s a bunch of stuff and the percent is\r\n5% - another percent\r\n6%";
$order   = array("\r\n", "\n", "\r");
$replace = '<br />';
$newstr = str_replace($order, $replace, $str);
$newstr = str_replace("\\", " ", $newstr);
This is assuming you don't want to convert them:

Code: Select all

$str     = "There\'s a bunch of stuff and the percent is\r\n5% - another percent\r\n6%";
$order   = array("\r\n", "\n", "\r");
$newstr = str_replace($order, " ", $str);
$newstr = str_replace("\\", " ", $newstr);
This code was taken from here:
http://www.php.net/manual/en/function.str-replace.php