0
$t = '"Confidence isn\'t gained over time and practice. Confidence is gained when you realize you choose your own path, you choose to fall, you choose not to fall.

If you are afraid to fall you fall because you are afraid. Everything is choice." - Daniel ILabaca';
$order   = array("\r\n", "\n", "\r");
$text = str_replace($order, '<br/>', $t);

But in the database is still the new line.

Before inserting I do htmlspecialchars(addslashes(trim($text)))

Ben
  • 1,906
  • 10
  • 31
  • 47
  • Your example works for me. Does the problem exists even with the example above? – hek2mgl Jan 12 '13 at 12:38
  • Whats the problem in keeping new lines in DB? – Shiplu Mokaddim Jan 12 '13 at 12:39
  • Because I use serialize() for caching. And the new line is a problem, since the $data[0] is the timestamp and $data[1] is the data. But when in the text there is new line they become more. – Ben Jan 12 '13 at 12:51

5 Answers5

2

Why don't you have a go with the nl2br() function? Try this:

$text = nl2br($t);

Instead of the following two rows that is:

$order   = array("\r\n", "\n", "\r");
$text = str_replace($order, '<br/>', $t);
karllindmark
  • 6,031
  • 1
  • 26
  • 41
  • Yes that do the job, but str_replace() fails. I will accept your answer after 9 mins.. – Ben Jan 12 '13 at 12:40
  • It should be noted that `nl2br` inserts a `
    ` tag before the newline, whereas the OP seems to want to remove the newline entirely.
    – Niet the Dark Absol Jan 12 '13 at 12:41
  • yes nl2br had to be mentioned. +1 But str_replace should work too. (And worked for me). The problem must be different – hek2mgl Jan 12 '13 at 12:41
2

While saving data in DB it only needs to be escaped to prevent SQL injection. No need to execute htmlspecialchars, nl2br, addslashes etc. You save the user data as it is. But make sure its safe. You should use htmlentities, nl2br, addslashes etc functions while displaying this data at the presentation layer.

Shiplu Mokaddim
  • 56,364
  • 17
  • 141
  • 187
0

If you don't want any linebreaks at all and don't want to have them converted to HTML <br > have a look at this here: Remove all the line breaks from the html source

Community
  • 1
  • 1
Stefan
  • 2,164
  • 1
  • 23
  • 40
0

You should use PHP built-in method nl2br()

nl2br — Inserts HTML line breaks before all newlines in a string 

Example

<?php
    echo nl2br("Welcome\r\nThis is my HTML document", false);
?>

Output

Welcome<br>
This is my HTML document
Irfan DANISH
  • 8,349
  • 12
  • 42
  • 67
0

Instead of the $order and str_replace bits, simply try $text = nl2br($t);

ggdx
  • 3,024
  • 4
  • 32
  • 48