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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
spincity
Forum Newbie
Posts: 2
Joined: Fri Mar 05, 2010 9:39 pm

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

Post 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!
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

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

Post by pbs »

Try nl2br() function
spincity
Forum Newbie
Posts: 2
Joined: Fri Mar 05, 2010 9:39 pm

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

Post 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.
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

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

Post by John Cartwright »

Apply stripslashes() prior to nl2br()

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