Skip to main content

Wrapping Text using PHP

Sometimes we need to wrap text to 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.
<?php
$text = “Sometimes we need to wrap text to exactly accommodate a certain width of text.”;
$newtext = wordwrap($text, 20, “
”);
echo $newtext;
?>

 

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 line at column 20 and return wrapped string.
<?php
$text = “Sometimes we need to wrap text to exactly accommodate a certain width of text.”;
$newtext = wordwrap($text, 20, “\n”);
echo $newtext;
?>

 

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!