PHP wordwrap() Function

Quick summary: The PHP wordwrap() function wraps a string to a given number of characters.

PHP wordwrap() Syntax

wordwrap(string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false): string
PHP

PHP wordwrap() Basic examples

echo wordwrap("This is a very long line of text", 10);
PHP
Output:
This is a
very long
line of
text

Wraps text at a specified line width.

PHP wordwrap() Real-world usage

$text = "Lorem ipsum dolor sit amet";
echo wordwrap($text, 8, "<br>");
PHP
Output:
Lorem<br>ipsum<br>dolor<br>sit<br>amet

Formats long text for HTML output.

PHP wordwrap() Edge cases

echo wordwrap("longword", 4, "\n", true);
PHP
Output:
long
word

Forces breaking long words.

PHP wordwrap() Common mistakes

Forgetting the cut parameter

Long words are not broken by default.

Incorrect
wordwrap("longword", 4);
Correct
wordwrap("longword", 4, "\n", true);

Enable the cut parameter to force word breaking.

PHP wordwrap() Frequently Asked Questions

What does wordwrap() do in PHP?

wordwrap() wraps a string to a given number of characters using a specified break string.

What is the syntax of wordwrap()?

wordwrap(string $string, int $width = 75, string $break = "\n", bool $cut = false): string

What does the width parameter do in wordwrap()?

It defines the maximum number of characters per line before wrapping.

What is the break parameter in wordwrap()?

It specifies the string inserted at line breaks, such as \n or <br>.

What does the cut parameter do in wordwrap()?

If true, long words are cut to fit the width; otherwise they are not broken.

Does wordwrap() modify the original string?

No, it returns a new wrapped string.

Can wordwrap() be used for HTML output?

Yes, by using <br> as the break parameter.

Does wordwrap() handle multibyte strings?

No, it is not multibyte-safe.

What happens if the string is shorter than width?

The string is returned unchanged.

Is wordwrap() useful for emails?

Yes, it is commonly used to format plain text emails.

Can wordwrap() break words incorrectly?

Only if the cut parameter is set to true.

What is a real-world use case of wordwrap()?

Formatting long text blocks for display or emails.

PHP wordwrap() Related PHP Functions