nl2br() : Inserting HTML Line breaks before all newlines in a string

$str="Welcome \n to plus2net";
echo nl2br($str);
Output
Welcome
to plus2net
Syntax
$string=nl2br($string);
To add line breaks in html we have to use <br> tags but to add this line break to any text entry from a form or from a text area we have to use the function nl2br() in PHP. This function nl2br() searches for all the line breaks or carriage returns within a string and replace them with line break tag or <br> tag. This way we can automatically add line breaks for a web page inside a string. Here is the syntax of nl2br() function.

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_EOL

To 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. )


String Functions strip_tags() To remove HTML tags from a string
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    vijay

    19-12-2014

    good one

    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer