Cannot replace \ n in php with content from database

I try to avoid asking stupid questions, but for some reason this just doesn't work. I am extracting some text from the database, including newlines. When using echo directly, this is the result:

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

Here is how I extracted it:

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

None of the following has any effect .....

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

HOWEVER, when I hardcode 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 database input, but ok with the manual string?

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; 
+4
source share
2 answers

When you do this:

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

Do you really see that \n printed on the output? Or is he actually printing a new line character?

If this is the first, then in the database row, instead of the newline, you use the newline escape line. In other words, your database row contains two characters \ and n , which do not make a new row.

Try replacing this replacement (or in addition to complete security):

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

the single quote syntax for a string causes php to not turn two \ and n characters into a newline character, so it should actually match what is in your database. (You can also use \\n , where the first slash skips the second slash, preventing it from turning into a new line.)

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

mysql_real_escape_string () calls the MySQL library function mysql_real_escape_string, which adds a backslash to the following characters: \ x00 , \ n , \ r , \,, " and \ x1a .

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

If you want to replace \n , you must look for it with single quotes - '\n' (instead of "\n" ) - these two have very different meanings in PHP.

+2
source

All Articles