Nl2br - Manual - PHP

  • Downloads
  • Documentation
  • Get Involved
  • Help
  • PHP 8.4
Search docs PHP 8.4.2 Released! Getting Started Introduction A simple tutorial Language Reference Basic syntax Types Variables Constants Expressions Operators Control Structures Functions Classes and Objects Namespaces Enumerations Errors Exceptions Fibers Generators Attributes References Explained Predefined Variables Predefined Exceptions Predefined Interfaces and Classes Predefined Attributes Context options and parameters Supported Protocols and Wrappers Security Introduction General considerations Installed as CGI binary Installed as an Apache module Session Security Filesystem Security Database Security Error Reporting User Submitted Data Hiding PHP Keeping Current Features HTTP authentication with PHP Cookies Sessions Handling file uploads Using remote files Connection handling Persistent Database Connections Command line usage Garbage Collection DTrace Dynamic Tracing Function Reference Affecting PHP's Behaviour Audio Formats Manipulation Authentication Services Command Line Specific Extensions Compression and Archive Extensions Cryptography Extensions Database Extensions Date and Time Related Extensions File System Related Extensions Human Language and Character Encoding Support Image Processing and Generation Mail Related Extensions Mathematical Extensions Non-Text MIME Output Process Control Extensions Other Basic Extensions Other Services Search Engine Extensions Server Specific Extensions Session Extensions Text Processing Variable and Type Related Extensions Web Services Windows Only Extensions XML Manipulation GUI Extensions Keyboard Shortcuts? This help j Next menu item k Previous menu item g p Previous man page g n Next man page G Scroll to bottom g g Scroll to top g h Goto homepage g s Goto search(current page) / Focus search box number_format » « nl_langinfo
  • PHP Manual
  • Function Reference
  • Text Processing
  • Strings
  • String Functions
Change language: English German Spanish French Italian Japanese Brazilian Portuguese Russian Turkish Ukrainian Chinese (Simplified) Other nl2br

(PHP 4, PHP 5, PHP 7, PHP 8)

nl2brInserts HTML line breaks before all newlines in a string

Description

nl2br(string $string, bool $use_xhtml = true): string

Returns string with <br /> or <br> inserted before all newlines (\r\n, \n\r, \n and \r).

Parameters

string

The input string.

use_xhtml

Whether to use XHTML compatible line breaks or not.

Return Values

Returns the altered string.

Examples

Example #1 Using nl2br()

<?phpecho nl2br("foo isn't\n bar");?>

The above example will output:

foo isn't<br /> bar

Example #2 Generating valid HTML markup using the use_xhtml parameter

<?phpecho nl2br("Welcome\r\nThis is my HTML document", false);?>

The above example will output:

Welcome<br> This is my HTML document

Example #3 Various newline separators

<?php$string = "This\r\nis\n\ra\nstring\r";echo nl2br($string);?>

The above example will output:

This<br /> is<br /> a<br /> string<br />

See Also

  • htmlspecialchars() - Convert special characters to HTML entities
  • htmlentities() - Convert all applicable characters to HTML entities
  • wordwrap() - Wraps a string to a given number of characters
  • str_replace() - Replace all occurrences of the search string with the replacement string

Found A Problem?

Learn How To Improve This Page • Submit a Pull Request • Report a Bug +add a note

User Contributed Notes 6 notes

up down 128 CGameProgrammer at gmail dot com19 years ago It's important to remember that this function does NOT replace newlines with <br> tags. Rather, it inserts a <br> tag before each newline, but it still preserves the newlines themselves! This caused problems for me regarding a function I was writing -- I forgot the newlines were still being preserved. If you don't want newlines, do: <?php $Result = str_replace( "\n", '<br />', $Text ); ?> up down 92 ngkongs at gmail dot com17 years ago to replace all linebreaks to <br /> the best solution (IMO) is: <?php function nl2br2($string) { $string = str_replace(array("\r\n", "\r", "\n"), "<br />", $string); return $string; } ?> because each OS have different ASCII chars for linebreak: windows = \r\n unix = \n mac = \r works perfect for me up down 46 N/A16 years ago Here's a more simple one:<?php/** * Convert BR tags to nl * * @param string The string to convert * @return string The converted string */function br2nl($string){ return preg_replace('/\<br(\s*)?\/?\>/i', "\n", $string);}?>Enjoy up down 18 fquffio at live dot it10 years ago Starting from PHP 4.3.10 and PHP 5.0.2, this should be the most correct way to replace <br /> and <br> tags with newlines and carriage returns.<?php/** * Convert BR tags to newlines and carriage returns. * * @param string The string to convert * @return string The converted string */function br2nl ( $string ){ return preg_replace('/\<br(\s*)?\/?\>/i', PHP_EOL, $string);}?>(Please note this is a minor edit of this function: http://php.net/nl2br#86678 )You might also want to be "platform specific", and therefore this function might be of some help:<?php/** * Convert BR tags to newlines and carriage returns. * * @param string The string to convert * @param string The string to use as line separator * @return string The converted string */function br2nl ( $string, $separator = PHP_EOL ){ $separator = in_array($separator, array("\n", "\r", "\r\n", "\n\r", chr(30), chr(155), PHP_EOL)) ? $separator : PHP_EOL; // Checks if provided $separator is valid. return preg_replace('/\<br(\s*)?\/?\>/i', $separator, $string);}?> up down 13 aabaev6 years ago double quotes !== single quotesphp > echo nl2br('\r\n');\r\nphp > echo nl2br("\r\n");<br /> up down 8 Anders Norrbring18 years ago Seeing all these suggestions on a br2nl function, I can also see that neither would work with a sloppy written html line break.. Users can't be trusted to write good code, we know that, and mixing case isn't too uncommon.I think this little snippet would do most tricks, both XHTML style and HTML, even mixed case like <Br> <bR /> and even <br > or <br />.<?phpfunction br2nl($text){ return preg_replace('/<br\\s*?\/??>/i', '', $text);}?> +add a note
  • String Functions
    • addcslashes
    • addslashes
    • bin2hex
    • chop
    • chr
    • chunk_​split
    • convert_​uudecode
    • convert_​uuencode
    • count_​chars
    • crc32
    • crypt
    • echo
    • explode
    • fprintf
    • get_​html_​translation_​table
    • hebrev
    • hex2bin
    • html_​entity_​decode
    • htmlentities
    • htmlspecialchars
    • htmlspecialchars_​decode
    • implode
    • join
    • lcfirst
    • levenshtein
    • localeconv
    • ltrim
    • md5
    • md5_​file
    • metaphone
    • money_​format
    • nl_​langinfo
    • nl2br
    • number_​format
    • ord
    • parse_​str
    • print
    • printf
    • quoted_​printable_​decode
    • quoted_​printable_​encode
    • quotemeta
    • rtrim
    • setlocale
    • sha1
    • sha1_​file
    • similar_​text
    • soundex
    • sprintf
    • sscanf
    • str_​contains
    • str_​decrement
    • str_​ends_​with
    • str_​getcsv
    • str_​increment
    • str_​ireplace
    • str_​pad
    • str_​repeat
    • str_​replace
    • str_​rot13
    • str_​shuffle
    • str_​split
    • str_​starts_​with
    • str_​word_​count
    • strcasecmp
    • strchr
    • strcmp
    • strcoll
    • strcspn
    • strip_​tags
    • stripcslashes
    • stripos
    • stripslashes
    • stristr
    • strlen
    • strnatcasecmp
    • strnatcmp
    • strncasecmp
    • strncmp
    • strpbrk
    • strpos
    • strrchr
    • strrev
    • strripos
    • strrpos
    • strspn
    • strstr
    • strtok
    • strtolower
    • strtoupper
    • strtr
    • substr
    • substr_​compare
    • substr_​count
    • substr_​replace
    • trim
    • ucfirst
    • ucwords
    • vfprintf
    • vprintf
    • vsprintf
    • wordwrap
  • Deprecated
    • convert_​cyr_​string
    • hebrevc
    • utf8_​decode
    • utf8_​encode
To Top ↑ and ↓ to navigate • Enter to select • Esc to close Press Enter without selection to search using Google

Từ khóa » Br Trong Php