I try this:
echo nl2br($row['content']);
But what I get is:
Hello everybody\n Good luck!
Why doesn't it convert the \n? the database is storing data as UTF-8.
In addition, I check it with a test string, and found out that if the string is with double quotes it doesn't work too.. I mean:
echo nl2br("Hello everybody\n Good luck");
It should work but if you wish you can try str_replace("\n","<br />") instead of nl2br.
The issue is that the text is being stored with an additional slash in your database. Use the stripslashes (PHP doc here) function on the text before nl2br (PHP doc here)
$myText = "Hello\\nWorld"; //text from a database (with line breaks escaped)
stripslashes(nl2br($myText));
print $myText;
// Result: Hello<br>World
I guess you have written to database \n as two characters, so it's not a "new line" character.
Try echo str_replace('\n','<br />', $row['content'])
Related
How to insert nl2br function with htmlspecialchars? I have a site where input is taken from textarea and nl2br is used to convert next line to a paragraph. When I tried with htmlspecialchars I got the below output. Here I wrote three 'test' words in textarea and saved in database. I am using htmlspecialchars to prevent html injections but because of this function nl2br function is not working. Can you tell be how to work around this problem?
test<br/>test<br/>test<br/>
yo do:
htmlspecialchars(nl2br($text));
you need:
nl2br(htmlspecialchars($text));
Call nl2br after you call htmlspecialchars:
echo nl2br(htmlspecialchars($the_text));
It's about using the right order,
htmlspecialchars(nl2br($string)); will produce the result you describe.
nl2br(htmlspecialchars($string)); will produce the result you wish.
nl2br
Inserts HTML line breaks before all newlines in a string
htmlspecialchars
Convert special characters to HTML entities
$text = "Hello \n World";
$unexpected_result = htmlspecialchars(nl2br($text)); // => "Hello <br /> World"
$expected_result = nl2br(htmlspecialchars($text)); // => "Hello <br/> World"
... That's why we need to use use htmlspecialchars before nl2br
PHP is echoing JavaScript (I'm using the jQuery library) something like this:
echo 'var users = $("#add").val().split("\n");';
However, the \n is creating a line break in what the echoed script looks like, and therefore breaking the JavaScript. Is there a way to circumvent this?
Many thanks!
The \n is an escape sequence meaning newline. Backslashes are the beginning of escape sequences, to output a backslash then write \\. So you want \\n. Other useful escape sequences include the quote: use \" to put a quote into the string instead of ending the string.
echo "var users = $(\"#add\").val().split(\"\\n\");";
Not sure If you looking for this
echo "<script>alert('Line1\\\\nThis still in Line1')</script>";
I am retrieving a product description value stored in database from admin through textarea upon form submit. When I select the description from database I get $description = $row['description']; and I would like to echo $description on main page like this: echo nl2br($description); but I see "\r\n" characters instead of making new rows. From what I've found here and on the net, your string must be used between double quotes, like this:
echo nl2br("Hello, \r\n This is the description");
Now, the value of $description from database is in fact "Hello, \r\n This is the description" but in my script I have to use it like this:
echo nl2br($description);
Which does not make br's, it is outputing \r\n instead. So, what can I do, I can't use double quotes here, from my experience.
You could translate them into their respective escape sequences before passing the string through nl2br(), like this:
$description = nl2br(str_replace('\\r\\n', "\r\n", $description));
But what are the literal escapes doing in your database in the first place?
You are storing the literal value of \r\n in your database, not the actual characters they represent.
Verify this in your database. If you see \r\n in the description field, then you're probably escaping the backslash when you're storing the data.
It looks like your text contains the individual characters \, r, \, and n, and does not contain actual newline characters. As such, str_replace() should get the job done:
echo str_replace('\r\n', '<br>', $description);
The nl2br can take a second (optional) argument for "is_xhtml" which will convert the \r\n into a <br> for you. Just change your line to:
echo nl2br($description, TRUE);
I can't get nl2br function to work after fetching data from my database:
$result = mysql_query("SELECT comments..etc.etc..");
while ($row = mysql_fetch_array($result))
{
echo nl2br($row["comments"]);
}
In database row comments:
\r\nThanks,\r\n
OUTPUT:
Same as in DB:
\r\nThanks,\r\n
If I simply test this out like so it works fine:
<?php
$mystring = "\r\nThanks,\r\n";
echo nl2br($mystring);
?>
OUTPUT:
converts \r \n to <br />
try this:
echo preg_replace('/\v+|\\\r\\\n/Ui','<br/>',$row["comments"]);
I know this is an old post but if like me you are have stumbled across this issue and the above didn't work for you, this solution may help you instead:
echo nl2br(stripslashes($row["comments"]));
or (they are not the same function, note the additional "c" after strip)
echo nl2br(stripcslashes($row["comments"]));
See original thread that helped me: nl2br() not working when displaying SQL results
Most likely you are doing escaping twice, when adding your data into DB.
Check your code that adds data to DB and remove unnecessary escaping.
Most likely it's some senseless "universal sanitization" function.
Well it's easy.
Let's take a quote, not a newline to demonstrate. The behavior the same.
Slashes being stripped then data goes to database.
Thus, in the normal case:
source: It's
after escaping: It\'s
by the query execution slash being stripped and
both in the database and back It's
in double escaping case:
source: It's
after escaping: It\'s
after second escaping: It\\\'s
by the query execution slash being stripped and
both in the database and back It\'s
we have our data spoiled.
Just make yourself understand that escaping i not something magical that makes your data "safe" (and, therefore can be done many times, as you probably think). It's just adding a backslash to certain symbols.
My guess is that the slashes in your DB are literal slashes (followed by n or r), not newlines. Can you find a way to store literal newlines in your database?
Following solution will work for both windows as well as for linux/unix machine
str_replace(array("\\r\\n", "\\r", "\\n"), "<br />", "string");
Make sure that you are not to using strings from file and/or set in single apostrophe. Because string is treated literally, and nl2br will not work.
NL2BR will work with double apostrophe.
Building on what Christian is saying, why don't you trying replacing the literal '\r\n' with "\r\n"?
Data you have stored is allready added the slashes.
You have to use stripslashes() first then str_replace()
stripslashes(str_replace('\r\n','<br/>',$row["comments"]))
For some reason this didn't work for me...
echo nl2br(stripcslashes($row["comments"]));
But this did...
$comments = stripcslashes($row["comments"]);
$commentsWithBreaks = nl2br($comments);
echo $commentsWithBreaks;
Not working for me either. I just did the following:
$mensaje = str_replace("
", "<br/>", $mensaje);
I was able to replace newline with <br> using this code :
str_replace(array("\r\n", "\r", "\n"), "<br>", "input");
(windows machine)
This could be a solution, at least it was for me.
$message = str_replace("\\r\\n", "<br>", $message);
It is possible that you are getting a string in which the slashes are escaped (i.e. \\) and nl2br works with \n\r not \\n\\r
Once you understand this, the solution is easy :)
For some reason I can't use \n to create a linefeed when outputting to a file with PHP. It just writes "\n" to the file. I've tried using "\\n" as well, where it just writes "\n" (as expected). But I can't for the life of me figure out why adding \n to my strings isn't creating new lines. I've also tried \r\n but it just appends "\r\n" to the line in the file.
Example:
error_log('test\n', 3, 'error.log');
error_log('test2\n', 3, 'error.log');
Outputs:
test\ntest2\n
Using MAMP on OSX in case that matters (some sort of PHP config thing maybe?).
Any suggestions?
Use double quotes. "test\n" will work just fine (Or, use 'test' . PHP_EOL).
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
http://php.net/manual/en/language.types.string.php
\n is not meant to be seen as a new line by the end user, you must use the html <br/> element for that.
/n only affects how the html that is generated by php appears in the source code of the web page. if you go to your web page and click on 'view source' you will see php-generated html as one long line. Not pretty. That's what \n is for ; to break that php-generated html into shorter lines. The purpose of \n is to make a prettier 'view source' page.
When you run a PHP script in a browser, it will be rendered as HTML by default. If the books you’re using show otherwise, then either the code or the illustration is inaccurate. You can use “view source” to view what was sent to the browser and you’ll see that your line feeds are present.
<?php
echo "Line 1\nLine 2";
?>
This will render in your browser as:
Line 1 Line 2
If you need to send plain text to your browser, you can use something like:
<?php
header('Content-type: text/plain');
echo "Line 1\nLine 2";
?>
This will output:
Line 1
Line 2
nl2br() function use for create new line
echo nl2br("Welcome\r\n This is my HTML document", false);
The above example will output:
Welcome
This is my HTML document
I'm pretty sure you are outputting to a html file.
The problem is html ignores newlines in source which means you have to replace the newlines with <br/> if you want a newline in the resulting page display.
You need to use double quotes. Double quotes have more escape chars.
error_log("test\n", 3, 'error.log');
error_log("test2\n", 3, 'error.log');
to place the \n in double quotes try
$LOG = str_replace('\n', "\n", $LOG);
It's because you use apostrophes ('). Use quotationmarks (") instead. ' prompts PHP to use whatever is in between the apostrophes literally.
Double quotes are what you want. Single quotes ignore the \ escape. Double quotes will also evaluate variable expressions for you.
Check this page in the php manual for more.
The “\n” or “\r” or similar tags are treated as white-space in HTML and browsers. You can use the "pre" tag to solve that issue
<?php
echo "<pre>";
echo "line1 \n some text \t a tab \r some other content";
echo "</pre>";
?>
If you want to print something like this with a newline (\n) after it:
<p id = "theyateme">Did it get eaten?</p>
To print the above, you should do this:
<?php
print('<p id = "theyateme">Did it get eaten?</p>' . "\n");
?>
The client code from above would be:
<p id = "theyateme">Did it get eaten?</p>
The output from above would be:
Did it get eaten?
I know it's hard, but I always do it that way, and you almost always have to do it that way.
Sometimes you want PHP to print \n to the page instead of giving a newline, like in JavaScript code (generated by PHP).
NOTE about answer: You might be like: Why did you use print instead of echo (I like my echo). That is because I prefer print over echo and printf, because it works better in some cases (my cases usually), but it can be done fine with echo in this case.