17

I'm pulling content from a DB that has been sanitized using mysql_real_escape_string. Accordingly the new line characters now appear as "\n". The issue is that this content is displayed to users inside a < pre > tag so I cannot replace \n with < br/> for instance.

I suppose I could replace \n with the actual utf8 character code before inserting the result inside the < pre>.

Can somoneone assist here? Not using mysql_real_escape_string isn't really an option due to security policy.

Thanks.

4
  • 1
    I'm a bit puzzled, normally your data should be returned unescaped. The way you describe it, it's as if the data went through mysql_real_escape_string() twice before being stored Commented Jul 16, 2010 at 11:34
  • It actually sounds like you over-sanitized the data by escaping it twice. If you put in mysql_real_escape_string("two\nlines"); there will be a real \n character in the database. If you get data out, there should be no need to replace \n back. If you keep it this way, expect problems with ' and " as well. Commented Jul 16, 2010 at 11:36
  • maybe you're a victim of the ludicrous "magic_quote" functionality in php - make sure that you disable it, it only confuses those who are aware of the concept of escaping. Commented Jul 16, 2010 at 11:40
  • Indeed it looks like the data was escaped twice. I'm using Zend_db and it seems that it's using mysql_real_escape_string by default. Commented Jul 19, 2010 at 8:33

5 Answers 5

28
echo '<pre>'.str_replace('\n', "\n", $string).'</pre>';
Sign up to request clarification or add additional context in comments.

2 Comments

this would work as a 'quick fix'. The root cause is the data being escaped twice
This didn't work until I used double quotes "\n" instead of single quotes '\n' for some reason.
7

why not ...

echo str_replace('\\n', PHP_EOL, "few lines\nof text here,\nblah, blah! etc!");

Comments

6
str_replace("\\n","\n",$data);

Comments

1

I'm pulling content from a DB that has been sanitized using mysql_real_escape_string. Accordingly the new line characters now appear as "\n"

If you've not done anything to the raw data pulled back from the database then the ptoblem is that it has been 'sanitized' twice when inserted.

C.

Comments

-2

This might help a bit:

echo('test\ntest'); shows as

test test

but echo("test\ntest"); shows as

test

test

1 Comment

echo('test\ntest'); should appear as test\ntest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.