Recipe 1.15. Wrapping Text at a Certain Line Length


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

1.15.2. Solution

Use wordwrap( ) :

<?php $s = "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."; print "<pre>\n".wordwrap($s)."\n</pre>"; ?>

This prints:

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

1.15.3. Discussion

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

<?php print wordwrap($s,50); ?>

This prints:

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 line breaks. For double spacing, use "\n\n":

<?php print wordwrap($s,50,"\n\n"); ?>

This prints:

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:

<?php print wordwrap('jabberwocky',5); print wordwrap('jabberwocky',5,"\n",1); ?>

This prints:

jabberwocky jabbe rwock y

1.15.4. See Also

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




PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net