string wordwrap ( string source [, int width [, string break [, boolean 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 a lot, 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 likely 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:
<?php
$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, wordwrap() will always wrap when it hits 20 characters or under - not 21, 22, etc. The only exception to this is if you have words that are individually longer than 20 characters - wordwrap() will not break up a word, and so may return larger chunks than the limit you set.
If you really want your limit to be a hard maximum, you can supply 1 as a fourth parameter, which enables "cut" mode - words over the limit will be cut up if this is enabled. Here is an example of cut mode in action:
<?php
$text = "Micro-organism is a very long word.";
$text = wordwrap($text, 6, "\n", 1);
print $text;
?>
That will output the following:
Micro-
organi
sm is
a very
long
word.
Want to learn PHP 7?
Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!
If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!
Next chapter: Changing string case >>
Previous chapter: Trimming whitespace
Jump to:
Home: Table of Contents
Copyright ©2015 Paul Hudson. Follow me: @twostraws.