1.12. Wrapping Text at a Certain Line Length

Problem

You need to wrap lines in a string. For example, you want to display text in <pre>/</pre> tags but have it stay within a regularly sized browser window.

Solution

Use wordwrap( ) :

$s = "Four score and seven years ago our fathers brought forth on this continen
t a new nation, conceived in liberty and dedicated to the proposition that all 
men are created equal.";

print "<pre>\n".wordwrap($s)."\n</pre>";
<pre>
               Four score and seven years ago our fathers brought forth on this continent
               a new nation, conceived in liberty and dedicated to the proposition that
               all men are created equal.
               </pre>

Discussion

By default, wordwrap( ) wraps text at 75 characters per line. An optional second argument specifies different line length:

print wordwrap($s,50);
Four score and seven years ago our fathers brought
               forth on this continent a new nation, conceived in
               liberty and dedicated to the proposition that all
               men are created equal.

Other characters besides “\n” can be used for linebreaks. For double spacing, use “\n\n”:

print wordwrap($s,50,"\n\n");
Four score and seven years ago our fathers brought

               forth on this continent a new nation, conceived in

               liberty and dedicated to the proposition that all

               men are created equal.

There is an optional fourth argument to wordwrap( ) that controls the treatment of words that are longer than the specified line length. If this argument is 1, these words are wrapped. Otherwise, they span past the specified line length:

print wordwrap('jabberwocky',5);
print wordwrap('jabberwocky',5,"\n",1);
jabberwocky

               jabbe
               rwock
               y

See Also

Documentation on wordwrap( ) at http://www.php.net/wordwrap.

Get PHP Cookbook 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.