PHP nl2br() Function
The nl2br() function in PHP inserts HTML line breaks before all newlines in a string.
Syntax
1 2 3 |
nl2br ( string $string [, bool $is_xhtml] ) |
Parameter
sting(required)- This parameter specifies the input string.
is_xhtml(optional)- This parameter states whether to use XHTML compatible line breaks or not.. The default value is true.
Return
This function returns the altered string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).
Example 1
1 2 3 4 5 6 7 8 |
<?php $str= "Hello\nExample\nand\nTutorial"; echo "String: ".$str; // inserting line breaks (<br> or <br />) in front of each newline (\n) in a string. echo "\nAfter using the 'nl2br()' function...\nNew Sring: ".nl2br($str); ?> |
Output
1 2 3 4 5 6 7 8 9 10 11 |
String: Hello Example and Tutorial After using the 'nl2br()' function... New Sring Hello<br> Example<br> and<br> Tutorial |
Example 2
1 2 3 4 5 6 7 8 |
<?php $str = "This\r\nis\n\ra\nnl2br() example"; echo "String: ".$str; // inserting line breaks (<br> or <br />) in front of each newline (\n) in a string. echo "\nAfter using the 'nl2br()' function...\nNew Sring: ".nl2br($str); ?> |
Output
1 2 3 4 5 6 7 8 9 10 11 |
String: This is a nl2br() example After using the 'nl2br()' function... New Sring: This<br> is<br> a<br> nl2br() example |
Example 3
1 2 3 4 5 6 7 8 9 |
<?php $str = "This is a\nnl2br() example"; echo "String: ".$str; // inserting line breaks (<br> or <br />) in front of each newline (\n) in a string. echo "\nAfter the nl2br() function...\n"; echo nl2br($str,false); // passed false will return <br> instead of </br> ?> |
Output
1 2 3 4 5 6 7 |
String: This is a nl2br() example After the nl2br() function... This is a<;br> nl2br() example |