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.

Laeeq

A web developer who has a love for creativity and enjoys experimenting with various techniques in both web design and development. If you would like to be kept up to date with our posts, you can follow us on Twitter, or even by subscribing to our RSS Feed.

One thought on “Wrapping Text using PHP

Leave a Reply

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

WordPress SEO fine-tune by Meta SEO Pack from Poradnik Webmastera