MaxQ
MaxQ

Reputation: 605

can't replace \n in php with content from database

I try to avoid asking stupid questions, but this for some reason is just not working. I'm retrieving some text from a database, with newlines included. When using echo straight away, this is the output:

=== BOLD TEXT ===\nHere is some text.

This is how i retrieved it:

$row = $query->row();
$content=$row->course_content;

Neither of the following have any effect.....

$content= str_replace(array("\r\n", "\r", "\n"), "<br />", $content); 
$content= str_replace("\n", " ", $content);
$content = nl2br($content);

HOWEVER, when i hard code it in a string to the original statement,

$content="=== BOLD TEXT ===\nHere is some text.";

pang! it works... any ideas as to why it refuses to accept the database input, but is fine with the manual string?

Complete Code:

//Switch between these two:
$row = $query->row();
$content=$row->course_content;
$content="=== BOLD TEXT ===\nHere is some text.";
$content = str_replace(array("\r\n", "\r", "\n"), "<br />", $content); 
$content = str_replace("\n", " ", $content);
$content = nl2br($content);     
echo $content;

Upvotes: 5

Views: 2932

Answers (2)

Patrick M
Patrick M

Reputation: 10989

When you do this:

$row = $query->row();
$content=$row->course_content;
echo $content;

Do you actually see the \n printed to the output? Or does it actually print a new line character?

If it's the former, then you have an escaped newline in your database string instead of an actual newline character. In other words, your database string contains two characters \ and n, which does not a newline make.

Try this replacement instead (or in addition to, to be completely safe):

$content = str_replace(array('\r\n', '\r', '\n'), "<br />", $content); 

The single quotes syntax for the string causes php to not turn the two characters \ and n into a newline character, thus it should actually match what's in your database. (You could also use \\n, where the first slash escapes the second slash, preventing it from turning into a newline.)

Edit: To answer your question, assuming you meant mysql_real_escape_string, then yes, this was expected behavior. From the documentation:

mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \ , ', " and \x1a.

Upvotes: 5

Emanuil Rusev
Emanuil Rusev

Reputation: 35235

$content="=== BOLD TEXT ===\nHere is some text.";

If you want to replace the \n, you should search for it using single quotes - '\n' (instead of "\n") - the two have very different meanings in PHP.

Upvotes: 3

Related Questions