It is unfeasible to say which solution is appropriate for the specific case of the question-author, but the original data in the database is usually kept the way you presented it in the question.
The database is saved as "plain / text". PHP has nothing to do with not "breaking the line automatically in HTML" because the data is in "plain text" plain / text .
The question is old, but I will demonstrate other means to other people who may have the same doubt and need solutions other than those presented.
textarea
One problem with trying to resolve replacing in the database with <br>
is when you need to display inside a textarea, for example:
<?php
$str = '0 Anos\n3 Dias';
?>
<textarea><?php echo $str;?></textarea>
A textarea will display the plain / text format and line breaks will be interpreted.
<textarea>0 Anos
3 Dias</textarea>
But if the text already comes with the <br>
tag of the database, textarea literally displays the text:
<textarea>0 Anos<br>3 Dias</textarea>
If you print outside a textarea, in the browser interface you will see a result without a line break:
<?php
$str = '0 Anos\n3 Dias';
?>
<div><?php echo $str;?></div>
It will result in 0 Anos3 Dias
, on a single line.
But note the result of the source code (press CTRL + U in Chrome). You will see the result in plain / text:
0 Anos
3 Dias
Using the <pre>
tag
You can solve this in several ways. A simple way is with the HTML features themselves. The <pre>
tag interprets line breaks (\ n or \ r)
<?php
$str = '0 Anos\n3 Dias';
?>
<pre><?php echo $str;?></pre>
The visual result of the browser will be this, even without the tag <br>
:
0 Anos
3 Dias
Converting with JavaScript
If you want to convert line breaks to <br>
, you can save processes on the server (PHP) side by using JavaScript to convert.
I recommend a phpjs.org function:
function nl2br (str, is_xhtml) {
var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br ' + '/>' : '<br>' // Adjust comment to avoid issue on phpjs.org display
return (str + '')
.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2')
}
The usage is identical to the nl2br () function of PHP.
Interpreting with CSS
Please be aware that this depends on your browser version:
<style>
p {
white-space: pre;
}
</style>
<p><?php echo '0 Anos\n3 Dias';?></p>
See: link