Current Location: Home> Latest Articles> PHP wordwrap Function Usage Guide: How Beginners Can Quickly Master Its Basic Operations?

PHP wordwrap Function Usage Guide: How Beginners Can Quickly Master Its Basic Operations?

gitbox 2025-08-26

PHP wordwrap Function Usage Guide: How Beginners Can Quickly Master Its Basic Operations?

In PHP development, handling long text often requires automatic line breaks. Without proper handling, the output may appear incomplete or messy in the browser. PHP provides a very practical function that makes implementing automatic line breaks easy.

1. Basic Syntax of the wordwrap Function

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

Parameter explanation:

  • $string: Required, the string to be processed.
  • $width: Optional, the maximum number of characters per line, default is 75.
  • $break: Optional, the string used for line breaks, default is the newline character \n.
  • $cut: Optional, whether to force line breaks within words, default is false.

2. Basic Usage Examples of wordwrap

The simplest usage, only specifying the text to wrap:

$text = "PHP is a widely-used general-purpose scripting language, especially suitable for Web development.";
echo wordwrap($text, 20);

Output (maximum 20 characters per line):

PHP is a widely-used
general-purpose
scripting language,
especially suitable
for Web development.

3. Custom Line Breaks

The default line break is \n, but for displaying in HTML, use
:

echo wordwrap($text, 20, "<br>");

This allows line breaks to be displayed directly on web pages.

4. Forcing Line Breaks Within Words

Some long words may exceed the set width. You can use the fourth parameter $cut to force line breaks:

$text = "Supercalifragilisticexpialidocious is a very long word";
echo wordwrap($text, 10, "\n", true);

The output will force a line break every 10 characters, even within words.

5. Conclusion

For beginners, mastering the wordwrap() function is straightforward. Just remember a few key points:

  1. Specify the maximum line length with $width.
  2. Set the line break string as needed with $break. In HTML,
    is commonly used.
  3. Decide whether to allow line breaks within words with $cut.

Once you master these basics, whether outputting to the command line or displaying long text on web pages, PHP’s wordwrap() function can easily help you implement automatic line breaks and keep text formatting neat.