Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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, ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page