w3resource

PHP: nl2br() function

Description

The nl2br() function is used to insert HTML line breaks ('<br />') before all newlines (\n) in a string.

Version:

(PHP 4 and above)

Syntax:

nl2br(input_string)

Parameter:

Name Description Required /
Optional
Type
input_string The input string Required String
is_xhtml Whether XHTML compatible line breaks will be used or not. Optional Boolean

Return value:

Returns the altered string.

Value Type: String.

Pictorial Presentation

php-string-nl2br()

Example:

<?php
echo nl2br("w3resource \n. \ncom");
?>

Output:

w3resource
.
com 

View the example in the browser

See also

PHP Function Reference

Previous: metaphone
Next: number_format



PHP: Tips of the Day

PHP: Pass a PHP string to a JavaScript variable (and escape newlines)

<script>
  var myvar = <?php echo json_encode($myVarValue); ?>;
</script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $myVarValue encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Note that because json_encode escapes forward slashes, even a string that contains </script> will be escaped safely for printing with a script block.

Ref : https://bit.ly/34f0Dym