Inserting HTML Line breaks using PHP
The most practical use of this is when users enter their data in a text area and then the details are displayed back to the visitors. Here if the visitor has used line breaks inside the text area then while displaying the details we have to take care of line breaks. The main problem while displaying will be stretching of lines horizontally. Here the single function nl2br() will take care of this.
If you are using a text area where users are entering any message or data with line breaks then we have to retain the same format and replace all the carriage returns by
tags. This can be done at the time of inserting the record to database table so while displaying we need not take care of that and the message will be displayed the way the user has entered. But if you are giving the option of editing ( at that time or in future ) to the user then the same text you have to use br2nl() function and display them inside a text area. So the best way is to store the content of the user without using nl2br() function and at the point of displaying in a browser ( not inside a text box ) we can use nl2br() to ensure the line breaks. So store the content as it is without using nl2br() and only use it while showing in a browser.
Using PHP_EOLTo add line break in all platform we can use PHP_EOL , this will add line break in platform .
echo 'This is text part'.PHP_EOL;\n : Line break in Linux / Unix
\r : Max OS
\r\n : Windows Line break
Here is a demo of the use of this function. You can see how the data of the text area gets displayed with and without the line breaks. ( The only difference between the two is before displaying the second case nl2br() function is used. )
Subscribe to our YouTube Channel here
This article is written by plus2net.com team. https://www.plus2net.com