Name

wordwrap()

Synopsis

    string wordwrap ( string str [, int line_length
    [, string break_char [, bool cut]]] )

Although web pages wrap text automatically, there are two situations when you might want to wrap text yourself:

  • When printing to a console as opposed to a web page, text does not wrap automatically. Therefore, unless you want your users to scroll around, it is best to wrap text for them.

  • When printing to a web page that has been designed to exactly accommodate a certain width of text, allowing browsers to wrap text whenever they want will lead to the design getting warped.

In either of these situations, the wordwrap() function comes to your aid. If you pass a sentence of text into wordwrap() with no other parameters, it will return that same string wrapped at the 75-character mark using "\n" for new lines. However, you can pass both the size and new line marker as parameters two and three if you want to, like this:

    $text = "Word wrap will split this text up into smaller lines, which makes
    for easier reading and neater layout.";
    $text = wordwrap($text, 20, "<br />");
    print $text;

Running that script will give you the following output:

    Word wrap will split<br />this text up into<br />smaller lines, which<br />
    makes for easier<br />reading and neater<br />layout.

As you can see, wordwrap() has used <br />, a HTML new line marker, and split up words at the 20-character mark. Note that wordwrap() always pessimistically wraps words—that is, if you set the second parameter to 20, ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.