Welcome to our in-depth PHP tutorial on the wordwrap() function! By the end of this lesson, you'll be able to master this essential text formatting tool and apply it to your own projects. Let's dive right in!
wordwrap() function? πThe wordwrap() function is a PHP utility that breaks a given string into smaller lines of a specified length. It's very useful for controlling the width of text output and ensuring it fits nicely within containers, like HTML <div> elements or console windows.
wordwrap() function π‘The wordwrap() function takes two parameters:
$text: The text string to be formatted$width: The maximum line width (in characters) for the resulting linesHere's a simple example:
<?php
$text = "This is a very long string that needs to be wrapped into lines of 50 characters or less.";
$wrapped_text = wordwrap($text, 50);
echo $wrapped_text;
?>When you run this code, the output will be:
This is a very long string that needs to be wrapped
into lines of 50 characters or less.
By default, the wordwrap() function will add a \n (newline) character at the end of each line, ensuring the text is properly formatted.
wordwrap() usage π‘The wordwrap() function also has some additional options to make it even more versatile.
To break the text at word boundaries instead of arbitrary character positions, set the third parameter $break_on_newline to TRUE.
<?php
$text = "This is a very long string that needs to be wrapped into lines of 50 characters or less.";
$wrapped_text = wordwrap($text, 50, "\n", TRUE);
echo $wrapped_text;
?>Output:
This is a very long string that needs
to be wrapped into lines of 50 characters or less.
To add indentation to multi-line strings, use the fourth parameter $indent_string.
<?php
$text = "This is a multi-line string.
It will be nicely formatted with 4 spaces indentation.";
$indented_text = wordwrap($text, 40, "\n", TRUE, " ");
echo $indented_text;
?>Output:
This is a multi-line string.
It will be nicely formatted with 4 spaces indentation.
What is the purpose of the `wordwrap()` function in PHP?
How do you break the text at word boundaries using the `wordwrap()` function?