Skip to main content

Wrapping Text using PHP

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Shares

Subscribe For Latest Updates

Signup for our newsletter and get notified when we publish new articles for free!