Wrapping Text using PHP

May 1st, 2013 by Laeeq | 1 comment

Sometimes we need to wrap text to exactly accommodate a certain width of text or allowing browsers to wrap text whenever required. You can use PHP’s wordwrap() function to wrap a string into new lines when it reaches a specific length. This function limits text display to a particular column size, thereby allowing precise control over how text is rendered on a Web page. By default, wordwrap() wraps strings at column 75 using the standard newline sequence.

Below example is wrapping the text using br at column 20 and return wrapped string.

  1. <?php
  2. $text = “Sometimes we need to wrap text to exactly accommodate a certain width of text.”;
  3. $newtext = wordwrap($text, 20, “</br>”);
  4. echo $newtext;
  5. ?>

 

Running above script will give you the following output:

Sometimes we need to
wrap text to exactly
accommodate a
certain width of
text.

 

Below example is wrapping the text using new linw at column 20 and return wrapped string.

  1. <?php
  2. $text = “Sometimes we need to wrap text to exactly accommodate a certain width of text.”;
  3. $newtext = wordwrap($text, 20, “\n”);
  4. echo $newtext;
  5. ?>

 

Running above script will give you the following output:

Sometimes we need to
wrap text to exactly
accommodate a
certain width of
text.

You can subscribe to PHPZAG.COM posts by Email

 

Related Topics:

  • How to Remove Leading & Trailing White Spaces with PHP
  • Parse HTML/Web Pages with PHP
  • Block Multiple IP Addresses Using PHP
  • How much memory do PHP variables use?
  • Manipulating PHP arrays: push, pop, shift, unshift
  •  

     

    1. June 17th, 2013 at 16:12 | #1

      So simple and short article explains word wrap clearly.

    1. No trackbacks yet.