Page 1 of 1

Convert PHP "\"-escaped string to HTML formatting.

Posted: Fri Mar 05, 2010 10:00 pm
by spincity
Hello, I'm new here!

I have a string that is uses backslashes to escape special characters. For instance, this string:

Code: Select all

Test 1\n\\n\\n\nTest 2\n\'\'\'\nTest 3
^Each of the single-quotes should be preceded by a backslash. Not sure how to get this to display here. This is how the string appears when printed plainly to the page.

Should appear as:
Test 1
\n\n
Test 2
'''
Test 3
The string was obtained by double-escaping (with mysql_real_escape_string()) the contents of a textarea box. Is there a simple way that I can convert this string into HTML-formatted text? That is, <br> in place of \n and ' instead of \'. I was considering a regular expression replacement, but I couldn't figure out how to properly account for \\n (and the like).

I hope this makes sense. Let me know if you need any more information.

Thanks!

Re: Convert PHP "\"-escaped string to HTML formatting.

Posted: Sat Mar 06, 2010 3:17 am
by pbs
Try nl2br() function

Re: Convert PHP "\"-escaped string to HTML formatting.

Posted: Sat Mar 06, 2010 3:01 pm
by spincity
Thanks for the response.

I have tried the nl2br() function, but it doesn't work because the string does not contain any literal newlines, only escaped representations of them.

Re: Convert PHP "\"-escaped string to HTML formatting.

Posted: Sat Mar 06, 2010 5:34 pm
by John Cartwright
Apply stripslashes() prior to nl2br()

It sounds like you have magic quotes enabled, which is a big no no.