PHP wordwrap() - Wrap Text to Lines
In PHP programming, formatting output text on multiple lines is a common need—whether it's for better readability in emails, console output, or user interfaces. The wordwrap() function is a powerful, built-in PHP string function specifically designed to wrap a long string to a specified line width by breaking the string at word boundaries.
Introduction to PHP wordwrap()
The wordwrap() function in PHP splits a long string into shorter lines by inserting line breaks (by default, newlines) at specified character lengths. It helps ensure the output text does not overflow or become difficult to read in environments like email bodies, terminal output, or HTML displays.
By default, wordwrap() breaks at whitespace between words, so words are not cut awkwardly in the middle, preserving readability.
Prerequisites
- Basic knowledge of PHP syntax.
- Understanding of strings and string manipulation in PHP.
- PHP environment setup with PHP 5.x or higher (function available since PHP 4).
Setup Steps
To try out the wordwrap() function, ensure:
- You have a PHP runtime on your local machine (XAMPP, MAMP, LAMP, or PHP CLI).
- An editor for writing PHP code (VSCode, Sublime Text, PHPStorm, etc.).
- Create a
wordwrap_example.phpfile for testing.
PHP wordwrap() Syntax
string wordwrap(
string $string,
int $width = 75,
string $break = "\n",
bool $cut = false
)
$string: The input string to wrap.$width: Maximum line width (in characters) before wrapping. Default is 75.$break: The line break string to insert (e.g., "\n", "
"). Default is newline.$cut: Iftrue, words longer than$widthwill be split. Default isfalse.
Explained Examples
Example 1: Basic Word Wrapping
Wrap a long sentence at 20 characters per line, inserting newline characters:
<?php
$text = "PHP's wordwrap() function is useful to format long strings.";
echo wordwrap($text, 20);
?>
Output:
PHP's wordwrap() function is useful to format long strings.
Example 2: Custom Break Character (<br> tag for HTML)
Use the <br> tag to wrap text for web display:
<?php
$text = "Display wrapped text in HTML using the br tag.";
echo wordwrap($text, 15, "<br>\n");
?>
Output:
Display wrapped<br> text in HTML<br> using the br<br> tag.
Example 3: Force Cut Long Words
Split words longer than the width by setting $cut to true:
<?php
$text = "Supercalifragilisticexpialidocious is a long word.";
echo wordwrap($text, 10, "\n", true);
?>
Output:
Supercalif ragilistic expialidoc ious is a long word.
Best Practices
- Always choose meaningful line width based on output format (e.g., 70-80 for emails, 20-40 for CLI).
- For web content, use <br> or CSS for line breaks instead of newline characters.
- Use
$cut=falseto avoid splitting words, unless strict width is required. - Sanitize and encode user input before output to avoid injection vulnerabilities when using in HTML.
- Test output in the target display context (terminal, browser, email client).
Common Mistakes
- Forgetting to set the
$breakparameter for web output, resulting in text not visually wrapped. - Using
$cut=trueunnecessarily causing broken words and poor readability. - Assuming
wordwrap()will add indentation or preserve existing line breaks — it only inserts new breaks. - Not considering character encoding where multibyte characters can affect line length calculations.
- Directly echoing wrapped strings in HTML without proper encoding or CSS formatting.
Interview Questions
Junior Level
-
What does the PHP
wordwrap()function do?It splits a long string into multiple lines by inserting line breaks at specified character widths.
-
What is the default line width in
wordwrap()?75 characters.
-
Which parameter defines the line break character in
wordwrap()?The third parameter,
$break, specifies the line break string. -
Does
wordwrap()split words by default?No, it wraps on word boundaries unless
$cutis set totrue. -
Can the
wordwrap()function be used to wrap text for emails?Yes, it helps format email bodies to fit within a reasonable line length.
Mid Level
-
How can you wrap text with HTML line breaks using
wordwrap()?Pass <br> as the
$breakparameter to insert HTML line breaks. -
What happens if you set the
$cutparameter to true?Words longer than the specified width will be forcibly split at the width limit.
-
Explain a scenario where
wordwrap()should not be used.When handling multibyte UTF-8 strings without proper encoding awareness, as it may break multibyte characters incorrectly.
-
How does
wordwrap()handle existing newlines in the string?It does not modify existing newlines; it only inserts breaks where necessary.
-
How would you ensure safe display of wrapped text in HTML?
Combine
wordwrap()withhtmlspecialchars()and use <br> breaks or CSS styling.
Senior Level
-
How would you implement word wrapping that respects multibyte UTF-8 strings in PHP?
Use
mb_strcut()or other multibyte-safe functions combined with custom logic instead ofwordwrap(), which is not multibyte aware. -
Can
wordwrap()be used to process very large strings efficiently? What considerations apply?It is fine for moderate strings but might be inefficient for very large strings requiring streaming or chunked processing to improve memory performance.
-
Describe how you could adapt
wordwrap()for internationalization (i18n) use cases.Replace whitespace detection and line breaking rules with locale-specific word boundary analysis; possibly leverage PHP intl extensions.
-
What are the drawbacks of relying solely on
wordwrap()for text formatting in applications?It lacks multibyte character support, provides no language-aware line breaking, and does not manage indentation or other formatting nuances.
-
How would you debug issues where
wordwrap()appears to break words unexpectedly?Check the
$cutparameter, string encoding, and line width parameters to ensure they match expected behavior and that no invisible characters affect wrapping.
Frequently Asked Questions (FAQ)
Q1. What character encoding does wordwrap() support?
wordwrap() works on byte strings and does not provide native support for multibyte encodings like UTF-8. Use multibyte functions for UTF-8 strings.
Q2. Can I use wordwrap() to wrap strings with HTML tags inside?
You can, but it may break tags if line breaks split HTML elements. Preprocess or strip tags before wrapping for safe HTML output.
Q3. How to preserve existing line breaks when using wordwrap()?
wordwrap() does not remove or modify existing line breaks, so they remain intact in the output.
Q4. Is there a way to indent wrapped lines using wordwrap()?
No direct way. You need to post-process the wrapped string or use other string formatting techniques.
Q5. How do I wrap a string and convert the line breaks to windows style?
Set the $break parameter to "\r\n" when calling wordwrap(), e.g., wordwrap($string, 75, "\r\n").
Conclusion
PHP’s wordwrap() function is a simple and effective tool to wrap long strings to a specified width, improving text readability in many applications like CLI outputs, emails, and user interfaces. Understanding and applying its parameters—such as the wrap width, line break characters, and the cut behavior—allows you to format strings with precision. While it has some limitations around multibyte encodings and HTML content, it remains a valuable part of the PHP string manipulation toolbox. Always test your output in the target environment to ensure the wrapped text meets your formatting expectations.