PHP wordwrap() Function Tutorial 🎯

beginner
15 min

PHP wordwrap() Function Tutorial 🎯

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!

What is the PHP 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.

How to use the wordwrap() function πŸ’‘

The wordwrap() function takes two parameters:

  1. $text: The text string to be formatted
  2. $width: The maximum line width (in characters) for the resulting lines

Here's a simple example:

php
<?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.

Advanced wordwrap() usage πŸ’‘

The wordwrap() function also has some additional options to make it even more versatile.

Breaking on word boundaries

To break the text at word boundaries instead of arbitrary character positions, set the third parameter $break_on_newline to TRUE.

php
<?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.

Specifying the indentation for multi-line strings

To add indentation to multi-line strings, use the fourth parameter $indent_string.

php
<?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.

Quiz: Wordwrap() function πŸ’‘

Quick Quiz
Question 1 of 1

What is the purpose of the `wordwrap()` function in PHP?

Quick Quiz
Question 1 of 1

How do you break the text at word boundaries using the `wordwrap()` function?