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.
string wordwrap(string $string, int $width = 75, string $break = "\n", bool $cut = false)
Parameter explanation:
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.
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.
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.
For beginners, mastering the wordwrap() function is straightforward. Just remember a few key points:
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.