PHP - Wrapping Lines of Text with wordwrap()

Introduction

PHP wordwrap() function takes a single-line string of text and splits it into several lines using newline ("\n") characters.

It wrapps the lines at the ends of words to avoid splitting words.

To use it, pass the string to wrap, and the function returns the wrapped string:

Demo

<?php
$myString = "this is a test, this is a test, this is a test, this is a test,
    this is a test, this is a test, this is a test, this is a test, this is a test,
     this is a test, this is a test, this is a test, this is a test, this is a test,
    this is a test, this is a test, this is a test, this is a test, this is a test, 
    this is a test,";//from  w  w w.  ja va2s  . com

echo wordwrap($myString);
?>

Result

By default, wordwrap() makes sure each line is no longer than 75 characters, but you can change this by passing an optional second argument:

Demo

<?php

$myString = "this is a test, this is a test, this is a test, this is a test,
    this is a test, this is a test, this is a test, this is a test, this is a test,
     this is a test, this is a test, this is a test, this is a test, this is a test,
    this is a test, this is a test, this is a test, this is a test, this is a test, 
    this is a test,";//  w  w w.ja va 2  s  .c o m

echo wordwrap ($myString, 40);
?>

Result

To split lines using a different character or characters than the newline character, pass the character(s) as an optional third argument.

For example, by splitting the lines with the HTML line break element <br/>:

Demo

<?php

$myString = "this is a test, this is a test, this is a test, this is a test,
    this is a test, this is a test, this is a test, this is a test, this is a test,
     this is a test, this is a test, this is a test, this is a test, this is a test,
    this is a test, this is a test, this is a test, this is a test, this is a test, 
    this is a test,";//from   w  ww . j  av a 2  s  .  c o  m

echo wordwrap ($myString, 40, " <br/>");
?>

Result

To convert the newlines in a string to HTML <br/> elements, you can use PHP's nl2br() function.

It takes a string to convert as an argument and returns the string with all newlines converted to <br/>.

The function always wraps the string to the specified line width, even if this means splitting words that are longer than the line width.

Demo

<?php

$myString = "This string has averylongwordindeed.";
echo wordwrap ($myString, 10, " \n ");
echo " \n  \n ";/*from w  w w  .java  2s  .  c  o  m*/
echo wordwrap ($myString, 10, " \n ", true);
?>

Result

Related Topic