Word wrap in PHP
Did you know that doing word wrap in PHP is really really easy? It seems that starting PHP version 4.0.2 there is a function called "wordwrap" that does this thing.
It accepts 4 parameters (one required and 3 optional) :
- text to wrap (required)
- width of a line (optional, default is 75 characters)
- new line separator (optional, default is "n", for HTML output use "<br />")
- cut long words? set to true if you want to cut into words (optional, default is false)
Here are some usage examples :
$test = 'CodePax is a great learning resource.'; //word wrap at 10 characters $new1 = wordwrap($test,10); //word wrap at 4 characters, separate lines by '-' $new2 = wordwrap($test,4,'-'); //word wrap at 4 characters, separate lines by '-' but also break longer words $new3 = wordwrap($test,4,'-',true);
and the output of the code above :
$new1 will contain : CodePax is a great learning resource. $new2 will contain : CodePax-is a-great-learning-resource. $new3 will contain : Code-Pax-is a-grea-t-lear-ning-reso-urce-