PHP Reference ยท String Functions
PHP wordwrap() function
Reference for PHP wordwrap(): wrap text to a maximum line width, choose the break string, cut long words, and avoid common pitfalls with multibyte text.
wordwrap() inserts line breaks into a string so that no line is longer than a given width, breaking at spaces. It is useful for plain-text emails, console output and fixed-width reports.
By default lines are broken with "\n" at a width of 75 characters. A word longer than the width stays whole unless you ask wordwrap() to cut it.
<?php echo wordwrap("The quick brown fox sat over the lazy dog", 15, "\n");
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
wordwrap( string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false ): string
| Name | Description |
|---|---|
$string |
The text to wrap. |
$width |
The maximum line length, counted in bytes. Default 75. |
$break |
The string inserted at each break. Default "\n". |
$cut_long_words |
If true, words longer than $width are cut at the width. If false (default) they stay whole and the line is longer than $width. |
Return value: the wrapped string.
Errors: throws a ValueError if $break is empty, or if $width is 0 while $cut_long_words is true.
Usage notes
- Width is counted in bytes, not characters, so UTF-8 text with accents may wrap early and long words may be cut inside a character. Use
mb_strimwidth()or a custom approach for multibyte text. - Breaks happen at spaces. Existing newlines in the input reset the line length, so paragraphs are kept.
- Not for HTML. Insert
<br>as$breakonly when you know the text has no tags; otherwise wrap in CSS. For line breaks in HTML output seenl2br(). - Break strings can be longer than one character, such as
"\r\n"for email bodies. - Cutting is a choice. Leave
$cut_long_wordsoff for URLs, which should stay whole. - It only inserts breaks. To join the lines again, replace the break string with a space.
Related
nl2br(),str_pad(),explode(),chunk_split(),ucwords()- Lessons: Strings, String formatting