nl2br() / wordwrap() Since: PHP 4(2000)
Converts newline characters to HTML line break tags, or wraps a long string at a specified width. Useful for displaying user-input text in HTML.
Syntax
// Inserts a <br> tag before each newline character. nl2br($string, $use_xhtml); // Wraps a string at a specified number of characters. wordwrap($string, $width, $break, $cut_long_words);
Function List
| Function | Description |
|---|---|
| nl2br($string, $use_xhtml) | Inserts <br /> before each newline character in the string. Set the second argument to false to insert <br> instead. |
| wordwrap($string, $width, $break, $cut_long_words) | Wraps the string every $width characters using $break. Set $cut_long_words to true to force a break even in the middle of a word. |
Return Value
Returns the converted string. The original string is not modified.
Sample Code
<?php
// Convert newline characters to <br> tags.
$text = "Line 1\nLine 2\nLine 3";
echo nl2br($text); // Inserts <br /> before each newline.
// In HTML5, using <br> is more common.
echo nl2br($text, false); // Inserts <br> instead of <br />.
// Safely display form input as HTML.
$comment = "Hello.\nI have a question about a product.\nThank you.";
echo nl2br(htmlspecialchars($comment, ENT_QUOTES, "UTF-8")); // Escape first, then convert newlines.
// Use wordwrap() to insert line breaks every N characters.
$str = "The quick brown fox jumps over the lazy dog";
echo wordwrap($str, 15, "\n"); // Inserts a newline every 15 characters.
// By default, wordwrap() does not break in the middle of a word.
echo wordwrap("Hello World Programming", 10, "\n"); // Breaks at word boundaries.
// Set the fourth argument to true to force breaks mid-word.
$long = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
echo wordwrap($long, 10, "\n", true); // Forces a break every 10 characters.
// Format an email body with wordwrap().
$body = "Thank you for your order. We are pleased to inform you that your item has been shipped.";
echo wordwrap($body, 30, "\n", true); // Wraps at 30 characters.
Notes
nl2br() converts newline characters in a string to HTML line break tags. Use it when you want to preserve a user's line breaks — for example, in comments or addresses entered in a textarea. As an XSS countermeasure, always escape the string with htmlspecialchars() before applying nl2br(). If you apply them in the wrong order, the <br> tags will be escaped and rendered as plain text.
wordwrap() wraps a string at a specified width. It is useful for formatting email bodies or plain-text output. By default, it does not break in the middle of a word, making it well-suited for English text. Setting the fourth argument to true forces breaks mid-word, but note that this may not work as expected with Japanese text, which has no space delimiters.
To replace parts of a string, use str_replace(). To split a string, use explode().
If you find any errors or copyright issues, please contact us.